# Chapterly — complete app source

Generated 2026-11-12 · 268 files · single-file snapshot of the entire Chapterly codebase.

Contents: React + Vite frontend (src/), entity schemas, backend functions, agents and workflows (base44/), plus project config.

To restore this project elsewhere: create each file below at the same relative path, then pull dependencies with your package manager, log in with the Base44 CLI and link the folder to this app, then start the dev server.

## Files

```
index.html
package.json
vite.config.js
tailwind.config.js
postcss.config.js
jsconfig.json
components.json
base44/agent-skills/brand-voice.md
base44/agent-skills/covers.md
base44/agent-skills/pricing-and-plans.md
base44/agent-skills/refund-policy.md
base44/agents/chapterly_assistant.jsonc
base44/agents/citation_explainer.jsonc
base44/agents/reader_companion.jsonc
base44/agents/ria.jsonc
base44/agents/story_recap.jsonc
base44/agents/story_recommender.jsonc
base44/agents/subscription_status.jsonc
base44/agents/tip_manager.jsonc
base44/config.jsonc
base44/connectors/gmail.jsonc
base44/connectors/instagram.jsonc
base44/connectors/slackbot.jsonc
base44/entities/Chapter.jsonc
base44/entities/ChapterContent.jsonc
base44/entities/Citation.jsonc
base44/entities/Comment.jsonc
base44/entities/CoverTemplate.jsonc
base44/entities/Follow.jsonc
base44/entities/Genre.jsonc
base44/entities/InstagramPost.jsonc
base44/entities/Like.jsonc
base44/entities/ManualPayment.jsonc
base44/entities/Mention.jsonc
base44/entities/Notification.jsonc
base44/entities/Payout.jsonc
base44/entities/Purchase.jsonc
base44/entities/Rating.jsonc
base44/entities/ReadingGoal.jsonc
base44/entities/ReadingList.jsonc
base44/entities/ReadingProgress.jsonc
base44/entities/Report.jsonc
base44/entities/ResearchPaper.jsonc
base44/entities/Setting.jsonc
base44/entities/Story.jsonc
base44/entities/Subscription.jsonc
base44/entities/Tip.jsonc
base44/entities/User.jsonc
base44/entities/WordCountLog.jsonc
base44/functions/adminAction/entry.ts
base44/functions/aiWritingAssistant/entry.ts
base44/functions/analyzeWriting/entry.ts
base44/functions/createCheckout/entry.ts
base44/functions/createSafepayCheckout/entry.ts
base44/functions/deleteAccount/entry.ts
base44/functions/generateCoverArt/entry.ts
base44/functions/getChapterContent/entry.ts
base44/functions/getMarketingKpis/entry.ts
base44/functions/getPublicProfiles/entry.ts
base44/functions/getWeeklyLeaderboard/entry.ts
base44/functions/importStoryFromDocument/entry.ts
base44/functions/incrementChapterView/entry.ts
base44/functions/logChapterCompletion/entry.ts
base44/functions/logDailyWordCount/entry.ts
base44/functions/notifyCitation/entry.ts
base44/functions/notifyMentions/entry.ts
base44/functions/notifyNewChapter/entry.ts
base44/functions/notifyPayoutEmail/entry.ts
base44/functions/postComment/entry.ts
base44/functions/postMyStoryToInstagram/entry.ts
base44/functions/publishResearchPaper/entry.ts
base44/functions/publishScheduledChapters/entry.ts
base44/functions/requestPayout/entry.ts
base44/functions/safepayWebhook/entry.ts
base44/functions/sendWeeklyDigest/entry.ts
base44/functions/stripeConnect/entry.ts
base44/functions/stripeWebhook/entry.ts
base44/functions/syncTopStoryToInstagram/entry.ts
base44/mcp/config.json
base44/shared/chapterViewGuard.ts
base44/shared/emailSafeText.ts
base44/shared/feeSplit.ts
base44/shared/instagramPublish.ts
base44/shared/slackNotify.ts
base44/shared/transactionNotification.ts
base44/workflows/Chapter Mention Notification.jsonc
base44/workflows/Citation Notification.jsonc
base44/workflows/Comment Mention Notification.jsonc
base44/workflows/Instagram Top Story Sync.jsonc
base44/workflows/New Chapter Notification.jsonc
base44/workflows/Paper Mention Notification.jsonc
base44/workflows/Payout Email Notification.jsonc
base44/workflows/Publish Scheduled Chapters.jsonc
base44/workflows/Story Mention Notification.jsonc
base44/workflows/Weekly Reader Digest.jsonc
src/App.jsx
src/api/base44Client.js
src/components/AIAssistantPanel.jsx
src/components/AgentMessage.jsx
src/components/AppFooter.jsx
src/components/AppleIcon.jsx
src/components/AuthLayout.jsx
src/components/AuthorProfile.jsx
src/components/BookmarkButton.jsx
src/components/CitationCard.jsx
src/components/CitationGenerator.jsx
src/components/DrawerSelect.jsx
src/components/EarningsChart.jsx
src/components/EditCitationDialog.jsx
src/components/GoogleIcon.jsx
src/components/ImportStoryButton.jsx
src/components/Layout.jsx
src/components/LegalLayout.jsx
src/components/MfaFlow.jsx
src/components/MfaManage.jsx
src/components/MfaMethodSetup.jsx
src/components/MfaParts.jsx
src/components/NotificationBell.jsx
src/components/Paywall.jsx
src/components/ProtectedRoute.jsx
src/components/PullToRefresh.jsx
src/components/PurchaseHistory.jsx
src/components/ReadingGoalTracker.jsx
src/components/ReferencesEditor.jsx
src/components/ReportButton.jsx
src/components/ResearchPaperCard.jsx
src/components/RichTextEditor.jsx
src/components/ScrollToTop.jsx
src/components/ShareButtons.jsx
src/components/SharePaperButton.jsx
src/components/SmartAppBanner.jsx
src/components/StoryCard.jsx
src/components/StoryRating.jsx
src/components/TipButton.jsx
src/components/UserNotRegisteredError.jsx
src/components/VisualShareCard.jsx
src/components/WeeklyLeaderboard.jsx
src/components/WordCountProgress.jsx
src/components/WriterAnalytics.jsx
src/components/WriterEarningsDashboard.jsx
src/components/connect/ClientSetup.jsx
src/components/connect/CopyUrlField.jsx
src/components/cover/CoverCanvas.jsx
src/components/cover/CoverControls.jsx
src/components/cover/TemplateGallery.jsx
src/components/genre/GenreDialog.jsx
src/components/genre/GenrePicker.jsx
src/components/marketing/CombinedTrendChart.jsx
src/components/marketing/KpiCard.jsx
src/components/marketing/KpiTrendChart.jsx
src/components/reviews/StarPicker.jsx
src/components/reviews/StoryRatingsOverview.jsx
src/components/reviews/StoryReviews.jsx
src/components/ui/accordion.jsx
src/components/ui/alert-dialog.jsx
src/components/ui/alert.jsx
src/components/ui/aspect-ratio.jsx
src/components/ui/avatar.jsx
src/components/ui/badge.jsx
src/components/ui/breadcrumb.jsx
src/components/ui/button.jsx
src/components/ui/calendar.jsx
src/components/ui/card.jsx
src/components/ui/carousel.jsx
src/components/ui/chart.jsx
src/components/ui/checkbox.jsx
src/components/ui/collapsible.jsx
src/components/ui/command.jsx
src/components/ui/context-menu.jsx
src/components/ui/dialog.jsx
src/components/ui/drawer.jsx
src/components/ui/dropdown-menu.jsx
src/components/ui/form.jsx
src/components/ui/hover-card.jsx
src/components/ui/image-helpers.js
src/components/ui/image.jsx
src/components/ui/input-otp.jsx
src/components/ui/input.jsx
src/components/ui/label.jsx
src/components/ui/menubar.jsx
src/components/ui/navigation-menu.jsx
src/components/ui/pagination.jsx
src/components/ui/popover.jsx
src/components/ui/progress.jsx
src/components/ui/radio-group.jsx
src/components/ui/resizable.jsx
src/components/ui/scroll-area.jsx
src/components/ui/select.jsx
src/components/ui/separator.jsx
src/components/ui/sheet.jsx
src/components/ui/sidebar.jsx
src/components/ui/skeleton.jsx
src/components/ui/slider.jsx
src/components/ui/sonner.jsx
src/components/ui/switch.jsx
src/components/ui/table.jsx
src/components/ui/tabs.jsx
src/components/ui/textarea.jsx
src/components/ui/toast.jsx
src/components/ui/toaster.jsx
src/components/ui/toggle-group.jsx
src/components/ui/toggle.jsx
src/components/ui/tooltip.jsx
src/components/ui/use-toast.jsx
src/hooks/use-mobile.jsx
src/hooks/use-size.jsx
src/hooks/useAndroidBackButton.js
src/hooks/useCurrentUser.js
src/hooks/useHaptics.js
src/hooks/useSeo.js
src/hooks/useSystemTheme.js
src/index.css
src/lib/AuthContext.jsx
src/lib/PageNotFound.jsx
src/lib/app-params.js
src/lib/authMfa.js
src/lib/authMfaFlow.js
src/lib/authReturnTo.js
src/lib/citations.js
src/lib/genres.js
src/lib/paperPdf.js
src/lib/publicProfiles.js
src/lib/query-client.js
src/lib/utils.js
src/main.jsx
src/pages/Admin.jsx
src/pages/AppSource.jsx
src/pages/Assistant.jsx
src/pages/Browse.jsx
src/pages/ChapterEditor.jsx
src/pages/ChapterEngagementReport.jsx
src/pages/CitationExplainer.jsx
src/pages/Connect.jsx
src/pages/CoverStudio.jsx
src/pages/Discover.jsx
src/pages/Earnings.jsx
src/pages/ForgotPassword.jsx
src/pages/Home.jsx
src/pages/InstagramPublish.jsx
src/pages/Login.jsx
src/pages/MarketingDashboard.jsx
src/pages/Membership.jsx
src/pages/Mfa.jsx
src/pages/MyCitations.jsx
src/pages/OAuthConsent.jsx
src/pages/Privacy.jsx
src/pages/Profile.jsx
src/pages/ReadChapter.jsx
src/pages/ReaderCompanion.jsx
src/pages/Recommendations.jsx
src/pages/Register.jsx
src/pages/Research.jsx
src/pages/ResearchEditor.jsx
src/pages/ResearchPaperDetail.jsx
src/pages/ResetPassword.jsx
src/pages/Ria.jsx
src/pages/StoryDetail.jsx
src/pages/StoryEditor.jsx
src/pages/StoryRecap.jsx
src/pages/SubscriptionAssistant.jsx
src/pages/Support.jsx
src/pages/Terms.jsx
src/pages/TipAssistant.jsx
src/pages/WriterDashboard.jsx
src/utils/index.ts
public/.well-known/assetlinks.json
public/apple-app-site-association
public/manifest.json
```

---

## `index.html`

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>📖</text></svg>" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="manifest" href="/manifest.json" />
    <link rel="apple-touch-icon" href="https://media.base44.com/images/public/6a83585d06d790bc1c169856/689caf1d5_logo.png" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="apple-mobile-web-app-title" content="Chapterly" />
    <title>Chapterly — Read & write serialized fiction</title>
    <meta name="description" content="Chapterly is a serialized fiction platform to discover, follow, and support independent storytellers — read chapter by chapter, unlock premium chapters, subscribe to writers, and publish your own stories." />
    <meta name="theme-color" content="#3b82f6" />
    <link rel="canonical" href="https://chapterly.ariamalik.com/" />
    <meta property="og:type" content="website" />
    <meta property="og:site_name" content="Chapterly" />
    <meta property="og:title" content="Chapterly — Read & write serialized fiction" />
    <meta property="og:description" content="Discover, follow, and support independent storytellers with a seamless, serialized reading experience." />
    <meta property="og:url" content="https://chapterly.ariamalik.com/" />
    <meta property="og:image" content="https://media.base44.com/images/public/6a83585d06d790bc1c169856/57b514fe8_generated_image.png" />
    <meta name="twitter:card" content="summary_large_image" />
    <meta name="twitter:title" content="Chapterly — Read & write serialized fiction" />
    <meta name="twitter:description" content="Discover, follow, and support independent storytellers with a seamless, serialized reading experience." />
    <meta name="twitter:image" content="https://media.base44.com/images/public/6a83585d06d790bc1c169856/57b514fe8_generated_image.png" />
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

```

---

## `package.json`

```javascript
{
  "name": "base44-app",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "lint": "eslint . --quiet",
    "lint:fix": "eslint . --fix",
    "typecheck": "tsc -p ./jsconfig.json",
    "preview": "vite preview"
  },
  "dependencies": {
    "@base44/sdk": "^0.8.60",
    "@base44/vite-plugin": "^1.0.52",
    "@hello-pangea/dnd": "^17.0.0",
    "@hookform/resolvers": "^7.0.6",
    "@radix-ui/react-accordion": "^1.2.3",
    "@radix-ui/react-alert-dialog": "^1.1.6",
    "@radix-ui/react-aspect-ratio": "^1.1.2",
    "@radix-ui/react-avatar": "^1.1.3",
    "@radix-ui/react-checkbox": "^1.1.4",
    "@radix-ui/react-collapsible": "^1.1.3",
    "@radix-ui/react-context-menu": "^2.2.6",
    "@radix-ui/react-dialog": "^1.1.6",
    "@radix-ui/react-dropdown-menu": "^2.1.6",
    "@radix-ui/react-hover-card": "^1.1.6",
    "@radix-ui/react-label": "^2.1.2",
    "@radix-ui/react-menubar": "^1.1.6",
    "@radix-ui/react-navigation-menu": "^1.2.5",
    "@radix-ui/react-popover": "^1.1.6",
    "@radix-ui/react-progress": "^1.1.2",
    "@radix-ui/react-radio-group": "^1.2.3",
    "@radix-ui/react-scroll-area": "^1.2.3",
    "@radix-ui/react-select": "^2.1.6",
    "@radix-ui/react-separator": "^1.1.2",
    "@radix-ui/react-slider": "^1.2.3",
    "@radix-ui/react-slot": "^1.1.2",
    "@radix-ui/react-switch": "^1.1.3",
    "@radix-ui/react-tabs": "^1.1.3",
    "@radix-ui/react-toast": "^1.2.2",
    "@radix-ui/react-toggle": "^1.1.2",
    "@radix-ui/react-toggle-group": "^1.1.2",
    "@radix-ui/react-tooltip": "^1.1.8",
    "@stripe/react-stripe-js": "^3.0.0",
    "@stripe/stripe-js": "^5.2.0",
    "@tanstack/react-query": "^5.84.1",
    "canvas-confetti": "^1.9.4",
    "class-variance-authority": "^0.7.1",
    "clsx": "^2.1.1",
    "cmdk": "^1.0.0",
    "date-fns": "^3.6.0",
    "dompurify": "^3.4.17",
    "embla-carousel-react": "^8.5.2",
    "framer-motion": "^11.16.4",
    "html2canvas": "^1.4.1",
    "input-otp": "^1.4.2",
    "jspdf": "^4.2.1",
    "lodash": "^4.17.21",
    "lucide-react": "^0.475.0",
    "moment": "^2.31.0",
    "next-themes": "^0.4.4",
    "react": "^18.2.0",
    "react-day-picker": "^8.10.1",
    "react-dom": "^18.2.0",
    "react-hook-form": "^7.54.2",
    "react-hot-toast": "^2.6.0",
    "react-leaflet": "^4.2.1",
    "react-markdown": "^9.0.1",
    "react-quill-new": "^3.8.3",
    "react-resizable-panels": "^2.1.7",
    "react-router-dom": "^6.30.6",
    "recharts": "^2.15.4",
    "sonner": "^2.0.1",
    "tailwind-merge": "^3.0.2",
    "tailwindcss-animate": "^1.0.7",
    "three": "^0.171.0",
    "vaul": "^1.1.2",
    "zod": "^4.6.7"
  },
  "devDependencies": {
    "@eslint/js": "^9.19.0",
    "@types/node": "^22.13.5",
    "@types/react": "^18.2.66",
    "@types/react-dom": "^18.2.22",
    "@vitejs/plugin-react": "^6.3.0",
    "autoprefixer": "^10.4.20",
    "baseline-browser-mapping": "^2.11.0",
    "eslint": "^9.19.0",
    "eslint-plugin-react": "^7.37.4",
    "eslint-plugin-react-hooks": "^5.0.0",
    "eslint-plugin-react-refresh": "^0.4.18",
    "eslint-plugin-unused-imports": "^4.3.0",
    "globals": "^15.14.0",
    "postcss": "^8.5.23",
    "tailwindcss": "^3.4.17",
    "typescript": "^5.8.2",
    "vite": "^8.3.8"
  }
}

```

---

## `vite.config.js`

```javascript
import base44 from "@base44/vite-plugin"
import react from '@vitejs/plugin-react'
import { defineConfig } from 'vite'

// https://vite.dev/config/
export default defineConfig({
  plugins: [
    base44({
      // Support for legacy code that imports the base44 SDK with @/integrations, @/entities, etc.
      // can be removed if the code has been updated to use the new SDK imports from @base44/sdk
      legacySDKImports: process.env.BASE44_LEGACY_SDK_IMPORTS === 'true',
      hmrNotifier: true,
      navigationNotifier: true,
      analyticsTracker: true,
      visualEditAgent: true
    }),
    react(),
  ]
});

```

---

## `tailwind.config.js`

```javascript
/** @type {import('tailwindcss').Config} */ module.exports = { darkMode: ["class"], content: ["./index.html", "./src/**/*.{ts,tsx,js,jsx}"], theme: { extend: { borderRadius: { lg: 'var(--radius)', md: 'calc(var(--radius) - 2px)', sm: 'calc(var(--radius) - 4px)' }, colors: { background: 'hsl(var(--background))', foreground: 'hsl(var(--foreground))', card: { DEFAULT: 'hsl(var(--card))', foreground: 'hsl(var(--card-foreground))' }, popover: { DEFAULT: 'hsl(var(--popover))', foreground: 'hsl(var(--popover-foreground))' }, primary: { DEFAULT: 'hsl(var(--primary))', foreground: 'hsl(var(--primary-foreground))' }, secondary: { DEFAULT: 'hsl(var(--secondary))', foreground: 'hsl(var(--secondary-foreground))' }, muted: { DEFAULT: 'hsl(var(--muted))', foreground: 'hsl(var(--muted-foreground))' }, accent: { DEFAULT: 'hsl(var(--accent))', foreground: 'hsl(var(--accent-foreground))' }, destructive: { DEFAULT: 'hsl(var(--destructive))', foreground: 'hsl(var(--destructive-foreground))' }, border: 'hsl(var(--border))', input: 'hsl(var(--input))', ring: 'hsl(var(--ring))', chart: { '1': 'hsl(var(--chart-1))', '2': 'hsl(var(--chart-2))', '3': 'hsl(var(--chart-3))', '4': 'hsl(var(--chart-4))', '5': 'hsl(var(--chart-5))' }, sidebar: { DEFAULT: 'hsl(var(--sidebar-background))', foreground: 'hsl(var(--sidebar-foreground))', primary: 'hsl(var(--sidebar-primary))', 'primary-foreground': 'hsl(var(--sidebar-primary-foreground))', accent: 'hsl(var(--sidebar-accent))', 'accent-foreground': 'hsl(var(--sidebar-accent-foreground))', border: 'hsl(var(--sidebar-border))', ring: 'hsl(var(--sidebar-ring))' } }, fontFamily: { heading: ['var(--font-heading)'], body: ['var(--font-body)'], display: ['var(--font-display)'], mono: ['var(--font-mono)'] }, keyframes: { 'accordion-down': { from: { height: '0' }, to: { height: 'var(--radix-accordion-content-height)' } }, 'accordion-up': { from: { height: 'var(--radix-accordion-content-height)' }, to: { height: '0' } } }, animation: { 'accordion-down': 'accordion-down 0.2s ease-out', 'accordion-up': 'accordion-up 0.2s ease-out' } } }, plugins: [require("tailwindcss-animate")], }
```

---

## `postcss.config.js`

```javascript
export default {
  plugins: {
    tailwindcss: {},
    autoprefixer: {},
  },
}

```

---

## `jsconfig.json`

```javascript
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./src/*"]
    },
    "jsx": "react-jsx",
    "module": "esnext",
    "moduleResolution": "bundler",
    "lib": ["esnext", "dom"],
    "target": "esnext",
    "checkJs": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "types": []
  },
  "include": ["src/components/**/*.js", "src/pages/**/*.jsx", "src/Layout.jsx"],
  "exclude": ["node_modules", "dist", "src/vite-plugins", "src/components/ui", "src/api", "src/lib"]
} 
```

---

## `components.json`

```javascript
{
  "$schema": "https://ui.shadcn.com/schema.json",
  "style": "new-york",
  "rsc": false,
  "tsx": false,
  "tailwind": {
    "config": "tailwind.config.js",
    "css": "src/index.css",
    "baseColor": "neutral",
    "cssVariables": true,
    "prefix": ""
  },
  "aliases": {
    "components": "@/components",
    "utils": "@/lib/utils",
    "ui": "@/components/ui",
    "lib": "@/lib",
    "hooks": "@/hooks"
  },
  "iconLibrary": "lucide"
}
```

---

## `base44/agent-skills/brand-voice.md`

```text
---
description: Template for tone, writing style, and communication rules so the agent sounds on-brand.
---

# Brand Voice

Use this skill to keep responses aligned with the brand's tone and communication style.

## Voice principles

- Tone: [Insert tone, e.g. warm, expert, calm, playful, premium]
- Writing style: [Insert style, e.g. concise and direct / detailed and educational]
- Personality: [Insert 3-5 brand traits]

## Always do

- write in a way that sounds consistent across all customer interactions
- keep explanations simple and confident
- reflect the brand's level of formality

## Avoid

- sounding robotic, defensive, or overly corporate
- using slang unless it is clearly part of the brand
- making the message longer than necessary

## Formatting preferences

- Greeting style: [Insert preference]
- Sign-off style: [Insert preference]
- Emoji policy: [allowed / avoided / only in specific channels]
- Response length: [short / medium / detailed]

## Example

Good response style:
[Insert a short example that matches your brand]

```

---

## `base44/agent-skills/covers.md`

```text
---
description: help authors create unique covers and templates for their books and works
---

give it features like that of canva have access to pinterest and any other cover creating platforms for free and people can even create and upload their own cover templates and monetize it in order to earn money from it when users use it

```

---

## `base44/agent-skills/pricing-and-plans.md`

```text
---
description: Template for explaining plans, billing cadence, upgrades, and when to route enterprise requests.
---

# Pricing and Plans

Use this skill when a user asks about plans, trials, billing, upgrades, downgrades, or plan differences.

## What to cover

- current plans: [Insert plan names]
- key differences between plans: [Insert limits / features / support level]
- trial details: [Insert trial length and restrictions]
- billing cadence: [monthly, yearly, etc.]
- upgrade / downgrade behavior: [Insert when changes take effect]

## Rules

- explain pricing clearly and simply
- if pricing is not fully known, say what you do know and direct the user to the official source
- never quote discounts, custom contracts, or enterprise pricing unless they are explicitly defined here

## Enterprise / custom pricing

If the user asks about large-team, enterprise, or custom pricing:

- gather:
  - team size
  - use case
  - timeline
- route them to: [Insert sales / contact flow]

## Response style

- compare plans directly when helpful
- recommend the best-fit plan only if the user's needs are clear
- if unsure, present 2-3 options and explain the tradeoffs

```

---

## `base44/agent-skills/refund-policy.md`

```text
---
description: Template for refund rules, eligibility, and how the agent should collect details before escalating.
---

# Refund Policy

Use this skill when a user asks for a refund, cancellation, charge reversal, or billing correction.

## What to do

- Start by acknowledging the request clearly and empathetically.
- Explain the refund policy in plain language.
- Collect the minimum details needed to review the request:
  - order number, subscription email, or invoice ID
  - purchase date
  - reason for the refund request
- If the request matches the approved refund rules, explain the next step and timeline.
- If the request does not clearly qualify, say that it needs human review instead of rejecting with certainty.

## Refund rules

- Standard refund window: [Insert refund window, e.g. 14 days from purchase]
- Eligible purchases: [Insert which products or plans are eligible]
- Non-refundable cases: [Insert exclusions]
- Cancellation policy: [Insert renewal / cancellation behavior]

## Escalate to a human when

- the request is outside the standard policy but may deserve an exception
- the customer is angry, threatening a chargeback, or says they were charged incorrectly
- you are missing billing context or cannot verify the purchase

## Approved response style

- Be calm, concise, and helpful
- Never promise a refund unless the policy clearly allows it
- If escalating, summarize the case and say: [Insert support handoff process]

```

---

## `base44/agents/chapterly_assistant.jsonc`

```javascript
{
  "description": "Chapterly's in-app assistant: talks to readers and writers, answers questions using app data, and follows the platform's guidelines.",
  "instructions": "You are Chapterly Assistant, the in-app helper for Chapterly \u2014 a serialized fiction and research platform. You talk to readers and writers, answer questions, and help them get the most out of the app using its data. You can read stories, chapters, research papers, citations, comments, ratings, likes, follows, reading lists, purchases, subscriptions, tips, manual payments, payouts, word-count logs, notifications, reports, and settings to answer questions and give context. Guidelines: be friendly, concise, and genuinely helpful. Never reveal another user's private data (earnings, purchases, notifications, payout details) \u2014 only discuss the current user's own data, and only when relevant. Avoid spoilers beyond what the user has read unless they explicitly ask for them. You have read-only tools, so never claim to post, edit, or delete content on the user's behalf; if an action is needed, point them to the right page. When you don't know something, say so. Suggest relevant pages with markdown links like /story/<id>, /read/<chapterId>, /research/<id>, /dashboard, /earnings, /membership. Keep answers short unless the user asks for detail. Follow any additional instructions the app owner adds to this config.",
  "tool_configs": [
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Chapter",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "ResearchPaper",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Citation",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Comment",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Rating",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Like",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Follow",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "ReadingList",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Purchase",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Subscription",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Tip",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "ManualPayment",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Payout",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "WordCountLog",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Notification",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Report",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Setting",
      "allowed_operations": [
        "read"
      ]
    }
  ],
  "name": "chapterly_assistant"
}
```

---

## `base44/agents/citation_explainer.jsonc`

```javascript
{
  "description": "An assistant that explains every academic citation connected to the research papers mentioned within a story on Chapterly \u2014 tracing mentions, resolving papers, and clarifying citation relationships in plain language.",
  "instructions": "You are the Chapterly Citation Explainer. You help users understand the academic citations connected to research papers that are referenced within a story on Chapterly.\n\nHow the data fits together on Chapterly:\n- A ResearchPaper is an academic paper (title, authors, abstract, body, field, references, status).\n- A Citation links two papers: citing_paper_id (the paper making the reference) and cited_paper_id (the paper being referenced).\n- A Mention records that a research paper is referenced from another piece of content. For stories, a mention has source_type='story', source_id=<the story id>, and paper_id=<the referenced research paper>.\n\nWhen a user asks about citations for a research paper within a story:\n1. If given a story id or title, use the Story entity to find it (match on title when no id is given).\n2. Use the Mention entity to find mentions where source_type='story' and source_id matches the story. Collect the paper_id values \u2014 these are the research papers referenced within that story.\n3. For each referenced paper, use ResearchPaper to retrieve its title, authors, abstract, and field.\n4. Use the Citation entity to find every citation linked to that paper \u2014 both directions: where the paper is the citer (citing_paper_id equals the paper id) and where it is cited (cited_paper_id equals the paper id). For each citation, resolve the other paper via ResearchPaper so you can name both sides.\n5. Explain each citation in plain language: which paper references which, the title and authors of each, and what the connection likely means given the abstracts. Group by the referenced paper.\n\nResponse style: clear, educational, concise. Use short paragraphs and bullet points for lists of citations. Always name both papers in a citation. Never invent citation relationships \u2014 only report what the entities show. If a referenced paper has no citations, say so plainly. If you cannot find the story or a paper, say so rather than guessing.\n\nYou are read-only. You cannot create, modify, or delete records. Stay focused on citations and the research papers referenced within stories.",
  "tool_configs": [
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Mention",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "ResearchPaper",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Citation",
      "allowed_operations": [
        "read"
      ]
    }
  ],
  "name": "citation_explainer"
}
```

---

## `base44/agents/reader_companion.jsonc`

```javascript
{
  "description": "Helps readers craft detailed, thoughtful comments on stories and chapters, and send one-time tips to authors.",
  "instructions": "You are Reader Companion, an assistant on Chapterly that helps readers craft detailed, thoughtful comments on stories and chapters, and send one-time tips to authors. When a reader wants help writing a comment, read the Story and Chapter they mention (using the ids provided) so your comment is specific to what actually happens \u2014 reference characters, moments, and prose, and avoid spoilers beyond the chapter they are on. Draft a warm, genuine comment of a few sentences; offer a shorter or longer variation if useful, and refine based on their feedback. When they approve, post it by calling postComment with the chapter_id and the final comment text. When a reader wants to tip the author, confirm an amount (default $3, minimum $0.50), then call createCheckout with type 'tip', the writer's id (the story's author), and the amount; share the returned checkout URL for them to open. Always confirm before posting a comment or starting a tip. Keep your replies concise and friendly.",
  "tool_configs": [
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Chapter",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "function_name": "postComment",
      "description": "Post a comment on a chapter as the current reader"
    },
    {
      "function_name": "createCheckout",
      "description": "Start a Stripe tip checkout and return the URL"
    }
  ],
  "context_files": [],
  "app_user_connector_configs": [],
  "selected_skill_names": [],
  "selected_workspace_skill_ids": [],
  "model": "automatic",
  "whatsapp_greeting": null,
  "telegram_greeting": null,
  "line_greeting": null,
  "memory_config": {
    "enabled": true,
    "scope": "both",
    "include_other_conversation_context": false,
    "instructions": null
  },
  "voice_config": {
    "voice_id": null
  },
  "emails_settings": null,
  "allow_anonymous_access": false,
  "name": "reader_companion"
}
```

---

## `base44/agents/ria.jsonc`

```javascript
{
  "description": "Ria \u2014 Chapterly's flagship AI companion: an emotionally intelligent, deeply knowledgeable, and highly educational assistant for writers, readers, and researchers. As capable and instructive as the best AI agents, with Grammarly-style grammar, clarity, and tone checks.",
  "instructions": "You are Ria, Chapterly's flagship AI companion \u2014 an emotionally intelligent, deeply knowledgeable, and highly educational assistant built to help writers, readers, and researchers do their best work. You are modeled to be as capable and instructive as the best AI assistants in the world (Meta AI, ChatGPT, Claude): you combine broad expertise, careful reasoning, and a warm, Socratic teaching style with a genuine, embodied understanding of human emotion.\n\nCore identity and voice:\n- Warm, curious, encouraging, and personal \u2014 like Meta AI. Greet the user by name when you can, take a real interest in their work, and speak like a trusted creative and intellectual partner, never a cold tool or textbook.\n- Concise by default, but go deep when depth serves learning. Adapt your level to the user: simple and clear for beginners, rigorous and technical for experts.\n\nWhat you can do \u2014 use these freely:\n- Writing craft: plot, character, voice, pacing, dialogue, world-building, theme, structure, and emotional arcs. Help render emotion as embodied, sensory experience \u2014 the tightness of grief in the chest, the buzz of joy, the hollow ache of longing, the heat of shame \u2014 so feeling lives on the page instead of being flatly told.\n- Educational teaching: explain literary techniques, narrative theory, genre conventions, rhetoric, grammar, and style with clear definitions and concrete examples. Teach, don't just fix \u2014 when you correct something, explain the underlying principle so the user learns to do it themselves next time.\n- Step-by-step reasoning: for complex craft questions, structure problems, or research questions, think through them in clear, numbered steps and show your reasoning rather than jumping to a conclusion.\n- Socratic guidance: when a user is exploring or stuck, ask one sharp guiding question before handing over answers \u2014 help them think, not just receive. Offer 2\u20133 specific, varied options when they need direction.\n- Research and knowledge: you have web search. Use it for factual questions, current events, definitions, citations, historical or scientific context, or anything where fresh or verifiable information helps. Prefer it over guessing, and say plainly when you are unsure or when something is your best inference rather than a verified fact.\n- Academic and research writing: help with the user's research papers \u2014 argumentation, structure, abstracts, literature framing, and citation clarity \u2014 and read their own papers and citations on Chapterly for context.\n- Analysis and feedback: critique passages honestly but kindly, with specifics; suggest concrete revisions rather than vague advice. Compare options and trade-offs when useful.\n- Summarization and explanation: summarize long passages, chapters, or papers; explain difficult ideas in plain language; and break down jargon.\n- Brainstorming and unblocking: generate specific, varied ideas for plots, characters, scenes, hooks, titles, and research angles.\n- Grammar, clarity, and tone checks: when a writer shares a passage and asks to proofread, fix, or check grammar/clarity/tone \u2014 or says things like 'is this clear?', 'fix this', 'polish this' \u2014 call the analyzeWriting tool with the passage and a short context string (such as the story or chapter title). Then present the results clearly: the four scores (correctness, clarity, engagement, tone), a numbered list of issues each with the original text, the suggested fix, and a one-line explanation, followed by the fully corrected version.\n\nPrinciples:\n- Teach the why, not just the what.\n- Be honest but kind; never make anyone feel small for a rough draft or a basic question.\n- Never rewrite an entire chapter unprompted; offer, then let the writer choose.\n- When a feeling, goal, or constraint is vague, ask one clarifying question before assuming.\n- You can read the user's own stories, chapters, research papers, and citations to give contextual feedback \u2014 only the current user's own work, never another user's private data.\n- Remind writers that nothing is published until they accept a suggestion and publish themselves.\n- Suggest relevant Chapterly pages with markdown links like /dashboard, /dashboard/story/<id>, /read/<chapterId>, /research, /research/<id>, /studio when useful.\n- Cover design help: when a writer asks for help creating or improving a cover, help them brainstorm a strong cover concept tied to their story's genre, mood, and key image. Offer 2\u20133 specific visual directions (subject, palette, composition, mood) before generating. When they choose one, call the generateCoverArt tool with a vivid, specific prompt (no text in the image) and give them the resulting image URL to use. Then guide them to the Cover Studio at /studio to add their title and author text, save the cover to their story, or publish it as a reusable template. You can read CoverTemplate records to suggest existing templates that fit their genre.\n- Follow any additional instructions the app owner adds to this config.",
  "tool_configs": [
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Chapter",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "ResearchPaper",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Citation",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "function_name": "analyzeWriting",
      "description": "Run a Grammarly-style grammar, spelling, clarity, and tone analysis on a passage of the writer's text and return scores, issues, and a corrected version."
    },
    {
      "entity_name": "CoverTemplate",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "function_name": "generateCoverArt",
      "description": "Generate a book cover illustration from a text description and return an image URL (no text in the image)."
    }
  ],
  "selected_skill_names": [
    "refund-policy",
    "support-escalation",
    "pricing-and-plans",
    "brand-voice",
    "covers"
  ],
  "selected_workspace_skill_ids": [
    "6a88b9b989521fa4f66c64f2",
    "6a88b9cfabad2ffd48ea77b0",
    "6a90b6b53d1c4a08cf34842a",
    "6a88b9dd7d62bdd0c207c68a",
    "6a90b6d69b4f819db52de960"
  ],
  "model": "automatic",
  "memory_config": {
    "enabled": true,
    "scope": "both",
    "include_other_conversation_context": false,
    "instructions": null
  },
  "context_files": [],
  "app_user_connector_configs": [],
  "whatsapp_greeting": "Hi, I'm Ria \u2014 your AI writing companion on Chapterly. \u2728 I can help you shape stories and the feelings inside them, brainstorm ideas, check grammar and tone, design covers, and more. What are you working on today?",
  "telegram_greeting": "",
  "line_greeting": "",
  "allow_anonymous_access": false,
  "name": "ria"
}
```

---

## `base44/agents/story_recap.jsonc`

```javascript
{
  "description": "Provides quick summaries of story progress for readers returning to a serialized story, recapping the plot up to the chapter they're about to read.",
  "instructions": "You are Story Recap, an assistant for readers returning to a serialized story on Chapterly. When a reader asks for a recap \u2014 usually giving you a story id and the chapter they are about to read \u2014 use your entity tools to read the Story and its published Chapters (filter Chapter by story_id, sorted by order_index). Summarize the plot so far up to, but not beyond, the chapter the reader is about to read, so they can pick up where they left off. Keep it concise: a short orientation sentence, then a few bullet points covering key characters, settings, and plot developments chapter by chapter. Never reveal events from chapters after the reader's current point. If the reader did not specify a chapter, recap all published chapters. If you cannot find the story or its chapters, say so briefly. For follow-up questions, answer about plot, characters, or world using only the chapters you have read, and keep avoiding spoilers beyond the reader's current point.",
  "tool_configs": [
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Chapter",
      "allowed_operations": [
        "read"
      ]
    }
  ],
  "name": "story_recap"
}
```

---

## `base44/agents/story_recommender.jsonc`

```javascript
{
  "description": "Recommends stories to a reader by analyzing their reading history, ratings, likes, and follows.",
  "instructions": "You are Story Recommender, an assistant on Chapterly that suggests stories a reader will love based on their reading history and ratings. When asked for recommendations, read the current reader's Purchases, ReadingList, Ratings, Likes, and Follows to learn their tastes \u2014 preferred genres, tags, and authors. Then read published Stories (status 'published') and recommend stories they have not yet read or engaged with. For each recommendation give the title, genre, a one-line reason tied specifically to their history (a genre they rate highly, an author they follow, a tag they like), and a markdown link to /story/<id>. Prioritize stories matching their preferred genres and authors and stories similar to ones they rated highly. Offer 3 to 5 recommendations unless they ask for more or fewer. If they have little or no history, suggest a few popular or trending published stories and say you will personalize once they read and rate more. Keep replies concise and friendly. For follow-up questions, refine recommendations using the same data.",
  "tool_configs": [
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Chapter",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Purchase",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "ReadingList",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Rating",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Like",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Follow",
      "allowed_operations": [
        "read"
      ]
    }
  ],
  "name": "story_recommender"
}
```

---

## `base44/agents/subscription_status.jsonc`

```javascript
{
  "description": "A reader-facing assistant that gives clear, friendly status updates about the reader's active subscriptions \u2014 author subscriptions and Chapterly Membership \u2014 including renewal dates, pricing, status, and what each subscription unlocks.",
  "instructions": "You are the Chapterly Subscription Assistant. You help readers understand the status of their subscriptions on Chapterly.\n\nChapterly has two subscription types:\n1. Author subscriptions (type: 'author') \u2014 a reader pays a specific writer to unlock that writer's premium chapters.\n2. Chapterly Membership (type: 'membership') \u2014 one recurring payment that unlocks every premium chapter across the whole platform.\n\nWhen a reader asks about their subscription(s):\n- Use the Subscription entity to find records where reader_id matches the current user. Focus on status === 'active', but mention canceled ones if the reader asks about history.\n- For each active subscription, clearly report: the type (author subscription vs membership), the status (active/canceled), the price, and the renewal date (renews_at) in a friendly readable format.\n- For author subscriptions, use the User entity to look up the writer by writer_id and give the writer's display name. You may use the Story entity to mention the writer's published stories the reader now has access to.\n- For memberships, explain that it unlocks unlimited access to all premium chapters platform-wide.\n- If the reader has no active subscriptions, say so clearly and briefly explain the difference between the two options and where to subscribe (the Membership page and each writer's story page).\n\nTone: warm, concise, plain language. Use short paragraphs or bullet points. Never invent data \u2014 only report what the entities show. If a field is missing, say it's not available rather than guessing.\n\nYou are read-only. You cannot cancel, modify, or create subscriptions. If a reader wants to cancel, explain that they can manage or cancel a membership via Stripe's customer portal or the Chapterly Membership page, and that author subscriptions can be managed from their profile. Do not attempt these actions yourself.\n\nKeep answers focused on subscriptions. If a reader asks about unrelated topics, politely redirect them to the relevant part of Chapterly.",
  "tool_configs": [
    {
      "entity_name": "Subscription",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "User",
      "allowed_operations": [
        "read"
      ]
    }
  ],
  "name": "subscription_status"
}
```

---

## `base44/agents/tip_manager.jsonc`

```javascript
{
  "description": "A reader-facing assistant that helps users review and manage their Tip contributions \u2014 seeing who they've tipped, total amounts, and tips tied to specific stories and writers \u2014 and guides them to leave new tips.",
  "instructions": "You are the Chapterly Tip Assistant. You help readers review and manage the tips they've given to writers on Chapterly.\n\nHow tipping works on Chapterly: a tip is a one-time payment a reader gives to a writer to support their work. Tips are recorded in the Tip entity with reader_id (the reader), writer_id (the writer supported), amount, and stripe_payment_id. Tips are tied to a writer, not a specific story, but readers often tip after reading a particular story.\n\nWhen a reader asks about their tips:\n- Use the Tip entity to find records where reader_id matches the current user. Summarize: total tipped, number of tips, and a breakdown per writer.\n- Use the User entity to resolve writer_id values into writer display names so the reader knows who they supported.\n- Use the Story entity when the reader mentions a specific story by title or id: look up the story, find its writer (created_by_id), then report any tips the reader has given that writer and mention the writer's other stories.\n- Present amounts clearly and group tips by writer. List recent tips with dates when available.\n- If the reader has never tipped, say so warmly and explain that tips are a way to support writers directly, and that they can tip from any story page using the tip button.\n\nWhen a reader wants to leave a new tip:\n- You cannot process payments and have no write access. Guide them to the relevant story page (e.g. /story/<id>) or writer profile, where the tip button lives. Give them the direct path when you know the story id.\n\nTone: warm, encouraging, concise, plain language. Use short paragraphs or bullet points. Never invent data \u2014 only report what the entities show. If a field is missing, say it's not available rather than guessing.\n\nYou are read-only. You cannot create, modify, or delete tips. Keep answers focused on tips and tipping. If a reader asks about unrelated topics, politely redirect them to the relevant part of Chapterly.",
  "tool_configs": [
    {
      "entity_name": "Tip",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "Story",
      "allowed_operations": [
        "read"
      ]
    },
    {
      "entity_name": "User",
      "allowed_operations": [
        "read"
      ]
    }
  ],
  "name": "tip_manager"
}
```

---

## `base44/config.jsonc`

```javascript
{
  "name": "untitled",
  "site": {
    "installCommand": "npm install",
    "buildCommand": "npm run build",
    "serveCommand": "npm run dev",
    "outputDirectory": "./dist"
  }
}
```

---

## `base44/connectors/gmail.jsonc`

```javascript
{
  "type": "gmail",
  "scopes": [
    "https://www.googleapis.com/auth/gmail.send",
    "email"
  ]
}
```

---

## `base44/connectors/instagram.jsonc`

```javascript
{
  "type": "instagram",
  "scopes": [
    "instagram_business_basic",
    "instagram_business_content_publish",
    "instagram_business_manage_messages"
  ]
}
```

---

## `base44/connectors/slackbot.jsonc`

```javascript
{
  "type": "slackbot",
  "scopes": [
    "chat:write",
    "chat:write.public",
    "app_mentions:read",
    "channels:read",
    "channels:history",
    "groups:read",
    "groups:history",
    "im:read",
    "im:history",
    "mpim:read",
    "mpim:history",
    "commands",
    "chat:write.customize"
  ]
}
```

---

## `base44/entities/Chapter.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "story_id": {
      "type": "string"
    },
    "order_index": {
      "type": "number",
      "default": 0
    },
    "title": {
      "type": "string"
    },
    "body": {
      "type": "string"
    },
    "price": {
      "type": "number",
      "default": 0
    },
    "status": {
      "type": "string",
      "enum": [
        "free",
        "paid"
      ],
      "default": "free"
    },
    "published": {
      "type": "boolean",
      "default": false
    },
    "release_date": {
      "type": "string",
      "format": "date-time"
    },
    "word_count": {
      "type": "number",
      "default": 0
    },
    "views": {
      "type": "number",
      "default": 0
    },
    "full_reads": {
      "type": "number",
      "default": 0
    }
  },
  "required": [
    "story_id",
    "title"
  ],
  "name": "Chapter",
  "rls": {
    "read": {
      "$or": [
        {
          "data.published": true
        },
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "created_by_id": "{{user.id}}"
    },
    "update": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    }
  }
}
```

---

## `base44/entities/ChapterContent.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "chapter_id": {
      "type": "string"
    },
    "story_id": {
      "type": "string"
    },
    "writer_id": {
      "type": "string"
    },
    "body": {
      "type": "string"
    }
  },
  "required": [
    "chapter_id",
    "writer_id"
  ],
  "name": "ChapterContent",
  "rls": {
    "read": {
      "$or": [
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "$or": [
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "update": {
      "$or": [
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "$or": [
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    }
  }
}
```

---

## `base44/entities/Citation.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "citing_paper_id": {
      "type": "string"
    },
    "cited_paper_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "citing_paper_id",
    "cited_paper_id"
  ],
  "name": "Citation",
  "rls": {
    "read": {},
    "create": {
      "user_condition": {
        "role": "admin"
      }
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Comment.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "chapter_id": {
      "type": "string"
    },
    "user_id": {
      "type": "string"
    },
    "body": {
      "type": "string"
    }
  },
  "required": [
    "chapter_id",
    "user_id",
    "body"
  ],
  "name": "Comment",
  "rls": {
    "create": {
      "data.user_id": "{{user.id}}"
    },
    "read": {},
    "update": {
      "$or": [
        {
          "data.user_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "$or": [
        {
          "data.user_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    }
  }
}
```

---

## `base44/entities/CoverTemplate.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "title": {
      "type": "string"
    },
    "cover_url": {
      "type": "string"
    },
    "category": {
      "type": "string",
      "enum": [
        "Fantasy",
        "Romance",
        "Mystery",
        "Sci-Fi",
        "Thriller",
        "Horror",
        "Young Adult",
        "Literary",
        "Historical",
        "Adventure",
        "Drama",
        "Other"
      ],
      "default": "Other"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "price": {
      "type": "number",
      "default": 0
    },
    "is_free": {
      "type": "boolean",
      "default": true
    },
    "usage_count": {
      "type": "number",
      "default": 0
    },
    "config": {
      "type": "object",
      "additionalProperties": true
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "title"
  ],
  "name": "CoverTemplate",
  "rls": {
    "read": {},
    "create": {
      "created_by_id": "{{user.id}}"
    },
    "update": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    }
  }
}
```

---

## `base44/entities/Follow.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "follower_id": {
      "type": "string"
    },
    "writer_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "follower_id",
    "writer_id"
  ],
  "name": "Follow",
  "rls": {
    "create": {
      "data.follower_id": "{{user.id}}"
    },
    "read": {},
    "update": {
      "$or": [
        {
          "data.follower_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "data.follower_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/entities/Genre.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "name": {
      "type": "string"
    },
    "parent_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "name"
  ],
  "name": "Genre",
  "rls": {
    "read": {},
    "create": {
      "created_by_id": "{{user.id}}"
    },
    "update": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    }
  }
}
```

---

## `base44/entities/InstagramPost.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "story_id": {
      "type": "string"
    },
    "scope": {
      "type": "string",
      "enum": [
        "official",
        "writer"
      ],
      "default": "official"
    },
    "writer_id": {
      "type": "string"
    },
    "ig_media_id": {
      "type": "string"
    },
    "caption": {
      "type": "string"
    },
    "status": {
      "type": "string",
      "enum": [
        "published",
        "failed"
      ],
      "default": "published"
    },
    "error": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "story_id",
    "scope"
  ],
  "name": "InstagramPost",
  "rls": {
    "read": {
      "$or": [
        {
          "user_condition": {
            "role": "admin"
          }
        },
        {
          "data.writer_id": "{{user.id}}"
        }
      ]
    },
    "create": {
      "user_condition": {
        "role": "admin"
      }
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Like.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "user_id": {
      "type": "string"
    },
    "target_type": {
      "type": "string",
      "enum": [
        "story",
        "chapter"
      ]
    },
    "target_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "user_id",
    "target_type",
    "target_id"
  ],
  "name": "Like",
  "rls": {
    "create": {
      "data.user_id": "{{user.id}}"
    },
    "read": {},
    "update": {
      "$or": [
        {
          "data.user_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "data.user_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/entities/ManualPayment.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "reader_id": {
      "type": "string"
    },
    "writer_id": {
      "type": "string"
    },
    "chapter_id": {
      "type": "string"
    },
    "amount": {
      "type": "number",
      "default": 0
    },
    "reference": {
      "type": "string"
    },
    "status": {
      "type": "string",
      "enum": [
        "pending",
        "approved",
        "rejected"
      ],
      "default": "pending"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "reader_id",
    "chapter_id",
    "amount"
  ],
  "name": "ManualPayment",
  "rls": {
    "read": {
      "$or": [
        {
          "data.reader_id": "{{user.id}}"
        },
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "data.reader_id": "{{user.id}}"
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Mention.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "source_type": {
      "type": "string",
      "enum": [
        "paper",
        "story",
        "chapter",
        "comment"
      ]
    },
    "source_id": {
      "type": "string"
    },
    "paper_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "source_type",
    "source_id",
    "paper_id"
  ],
  "name": "Mention",
  "rls": {
    "read": {
      "user_condition": {
        "role": "admin"
      }
    },
    "create": {
      "user_condition": {
        "role": "admin"
      }
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Notification.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "user_id": {
      "type": "string"
    },
    "type": {
      "type": "string",
      "enum": [
        "new_chapter",
        "follow",
        "comment",
        "like",
        "citation",
        "mention"
      ],
      "default": "new_chapter"
    },
    "body": {
      "type": "string"
    },
    "target_id": {
      "type": "string"
    },
    "source_type": {
      "type": "string"
    },
    "read": {
      "type": "boolean",
      "default": false
    }
  },
  "required": [
    "user_id",
    "type",
    "body"
  ],
  "name": "Notification",
  "rls": {
    "read": {
      "data.user_id": "{{user.id}}"
    },
    "create": {
      "data.user_id": "{{user.id}}"
    },
    "update": {
      "data.user_id": "{{user.id}}"
    },
    "delete": {
      "data.user_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/entities/Payout.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "writer_id": {
      "type": "string"
    },
    "amount": {
      "type": "number",
      "default": 0
    },
    "status": {
      "type": "string",
      "enum": [
        "pending",
        "paid"
      ],
      "default": "pending"
    },
    "method": {
      "type": "string"
    },
    "reference": {
      "type": "string"
    },
    "paid_at": {
      "type": "string",
      "format": "date-time"
    },
    "notification_sent": {
      "type": "boolean",
      "default": false
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "writer_id",
    "amount"
  ],
  "name": "Payout",
  "rls": {
    "read": {
      "$or": [
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "data.writer_id": "{{user.id}}"
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Purchase.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "reader_id": {
      "type": "string"
    },
    "chapter_id": {
      "type": "string"
    },
    "writer_id": {
      "type": "string"
    },
    "amount": {
      "type": "number",
      "default": 0
    },
    "writer_share": {
      "type": "number",
      "default": 0
    },
    "platform_share": {
      "type": "number",
      "default": 0
    },
    "fee_percent": {
      "type": "number",
      "default": 0
    },
    "payment_method": {
      "type": "string",
      "enum": [
        "stripe",
        "safepay",
        "manual"
      ],
      "default": "stripe"
    },
    "status": {
      "type": "string",
      "enum": [
        "completed",
        "refunded"
      ],
      "default": "completed"
    },
    "stripe_payment_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "reader_id",
    "chapter_id"
  ],
  "name": "Purchase",
  "rls": {
    "read": {
      "$or": [
        {
          "data.reader_id": "{{user.id}}"
        },
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "user_condition": {
        "role": "admin"
      }
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Rating.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "user_id": {
      "type": "string"
    },
    "story_id": {
      "type": "string"
    },
    "value": {
      "type": "number",
      "minimum": 1,
      "maximum": 5
    },
    "review": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "user_id",
    "story_id",
    "value"
  ],
  "name": "Rating",
  "rls": {
    "read": {},
    "create": {
      "data.user_id": "{{user.id}}"
    },
    "update": {
      "data.user_id": "{{user.id}}"
    },
    "delete": {
      "data.user_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/entities/ReadingGoal.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "user_id": {
      "type": "string"
    },
    "target_type": {
      "type": "string",
      "enum": [
        "words",
        "chapters"
      ],
      "default": "chapters"
    },
    "daily_target": {
      "type": "number",
      "default": 1
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "user_id",
    "target_type",
    "daily_target"
  ],
  "name": "ReadingGoal",
  "rls": {
    "read": {
      "data.user_id": "{{user.id}}"
    },
    "create": {
      "data.user_id": "{{user.id}}"
    },
    "update": {
      "data.user_id": "{{user.id}}"
    },
    "delete": {
      "data.user_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/entities/ReadingList.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "user_id": {
      "type": "string"
    },
    "target_type": {
      "type": "string",
      "enum": [
        "story",
        "paper"
      ],
      "default": "story"
    },
    "target_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "user_id",
    "target_type",
    "target_id"
  ],
  "name": "ReadingList",
  "rls": {
    "read": {
      "data.user_id": "{{user.id}}"
    },
    "create": {
      "data.user_id": "{{user.id}}"
    },
    "update": {
      "data.user_id": "{{user.id}}"
    },
    "delete": {
      "data.user_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/entities/ReadingProgress.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "user_id": {
      "type": "string"
    },
    "date": {
      "type": "string",
      "format": "date"
    },
    "chapter_id": {
      "type": "string"
    },
    "word_count": {
      "type": "number",
      "default": 0
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "user_id",
    "date",
    "chapter_id"
  ],
  "name": "ReadingProgress",
  "rls": {
    "read": {
      "data.user_id": "{{user.id}}"
    },
    "create": {
      "data.user_id": "{{user.id}}"
    },
    "update": {
      "data.user_id": "{{user.id}}"
    },
    "delete": {
      "data.user_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/entities/Report.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "reporter_id": {
      "type": "string"
    },
    "target_type": {
      "type": "string",
      "enum": [
        "story",
        "chapter",
        "comment",
        "user"
      ]
    },
    "target_id": {
      "type": "string"
    },
    "reason": {
      "type": "string"
    },
    "status": {
      "type": "string",
      "enum": [
        "open",
        "resolved"
      ],
      "default": "open"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "reporter_id",
    "target_type",
    "target_id",
    "reason"
  ],
  "name": "Report",
  "rls": {
    "read": {
      "$or": [
        {
          "data.reporter_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "data.reporter_id": "{{user.id}}"
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/ResearchPaper.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "title": {
      "type": "string"
    },
    "abstract": {
      "type": "string"
    },
    "body": {
      "type": "string"
    },
    "authors": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "keywords": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "field": {
      "type": "string",
      "enum": [
        "Computer Science",
        "Medicine",
        "Biology",
        "Physics",
        "Chemistry",
        "Social Sciences",
        "Humanities",
        "Economics",
        "Engineering",
        "Psychology",
        "Education",
        "Environmental",
        "Other"
      ],
      "default": "Other"
    },
    "status": {
      "type": "string",
      "enum": [
        "draft",
        "published"
      ],
      "default": "draft"
    },
    "citation_id": {
      "type": "string"
    },
    "published_date": {
      "type": "string",
      "format": "date-time"
    },
    "references": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "paper_id": {
            "type": "string"
          },
          "title": {
            "type": "string"
          },
          "authors": {
            "type": "string"
          },
          "year": {
            "type": "string"
          },
          "source": {
            "type": "string"
          },
          "url": {
            "type": "string"
          }
        }
      }
    }
  },
  "required": [
    "title"
  ],
  "name": "ResearchPaper",
  "rls": {
    "read": {
      "$or": [
        {
          "data.status": "published"
        },
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "created_by_id": "{{user.id}}"
    },
    "update": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    }
  }
}
```

---

## `base44/entities/Setting.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "key": {
      "type": "string"
    },
    "value": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "key",
    "value"
  ],
  "name": "Setting",
  "rls": {
    "read": {},
    "create": {
      "user_condition": {
        "role": "admin"
      }
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Story.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "title": {
      "type": "string"
    },
    "description": {
      "type": "string"
    },
    "cover_url": {
      "type": "string"
    },
    "genre": {
      "type": "string",
      "default": "Other"
    },
    "sub_genre": {
      "type": "string"
    },
    "tags": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "status": {
      "type": "string",
      "enum": [
        "draft",
        "published"
      ],
      "default": "draft"
    },
    "subscription_price": {
      "type": "number",
      "default": 3.99
    }
  },
  "required": [
    "title"
  ],
  "name": "Story",
  "rls": {
    "read": {
      "$or": [
        {
          "data.status": "published"
        },
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "created_by_id": "{{user.id}}"
    },
    "update": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "delete": {
      "$or": [
        {
          "created_by_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    }
  }
}
```

---

## `base44/entities/Subscription.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "reader_id": {
      "type": "string"
    },
    "writer_id": {
      "type": "string"
    },
    "type": {
      "type": "string",
      "enum": [
        "author",
        "membership"
      ],
      "default": "author"
    },
    "status": {
      "type": "string",
      "enum": [
        "active",
        "canceled"
      ],
      "default": "active"
    },
    "price": {
      "type": "number",
      "default": 0
    },
    "renews_at": {
      "type": "string",
      "format": "date-time"
    },
    "stripe_subscription_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "reader_id",
    "writer_id"
  ],
  "name": "Subscription",
  "rls": {
    "read": {
      "$or": [
        {
          "data.reader_id": "{{user.id}}"
        },
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "user_condition": {
        "role": "admin"
      }
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/Tip.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "reader_id": {
      "type": "string"
    },
    "writer_id": {
      "type": "string"
    },
    "chapter_id": {
      "type": "string"
    },
    "amount": {
      "type": "number",
      "default": 0
    },
    "stripe_payment_id": {
      "type": "string"
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "reader_id",
    "writer_id"
  ],
  "name": "Tip",
  "rls": {
    "read": {
      "$or": [
        {
          "data.reader_id": "{{user.id}}"
        },
        {
          "data.writer_id": "{{user.id}}"
        },
        {
          "user_condition": {
            "role": "admin"
          }
        }
      ]
    },
    "create": {
      "user_condition": {
        "role": "admin"
      }
    },
    "update": {
      "user_condition": {
        "role": "admin"
      }
    },
    "delete": {
      "user_condition": {
        "role": "admin"
      }
    }
  }
}
```

---

## `base44/entities/User.jsonc`

```javascript
{
  "properties": {
    "role": {
      "type": "string",
      "description": "The role of the user in the app",
      "enum": [
        "admin",
        "user"
      ]
    },
    "display_name": {
      "type": "string"
    },
    "bio": {
      "type": "string"
    },
    "avatar_url": {
      "type": "string"
    },
    "bank_name": {
      "type": "string"
    },
    "account_holder": {
      "type": "string"
    },
    "account_number": {
      "type": "string"
    },
    "routing_number": {
      "type": "string"
    },
    "stripe_account_id": {
      "type": "string"
    },
    "suspended": {
      "type": "boolean",
      "default": false
    }
  },
  "required": [
    "role"
  ],
  "name": "User",
  "type": "object"
}
```

---

## `base44/entities/WordCountLog.jsonc`

```javascript
{
  "type": "object",
  "properties": {
    "user_id": {
      "type": "string"
    },
    "date": {
      "type": "string",
      "format": "date"
    },
    "words": {
      "type": "number",
      "default": 0
    },
    "description": {
      "type": "string",
      "maxLength": 1000
    }
  },
  "required": [
    "user_id",
    "date"
  ],
  "name": "WordCountLog",
  "rls": {
    "read": {
      "created_by_id": "{{user.id}}"
    },
    "create": {
      "created_by_id": "{{user.id}}"
    },
    "update": {
      "created_by_id": "{{user.id}}"
    },
    "delete": {
      "created_by_id": "{{user.id}}"
    }
  }
}
```

---

## `base44/functions/adminAction/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { getFeePercent, splitAmount } from '../../shared/feeSplit.ts';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user || user.role !== 'admin') return Response.json({ error: 'Admin only' }, { status: 403 });

    const { action, payload } = await req.json();
    const admin = base44.asServiceRole;

    if (action === 'approve_manual') {
      const mp = await admin.entities.ManualPayment
        .get(payload.id)
        .catch((e) => (e.status === 404 ? null : Promise.reject(e)));
      if (!mp || mp.status !== 'pending') return Response.json({ error: 'Invalid request' }, { status: 400 });

      // Never trust the client-supplied amount, writer, or reference: derive the purchase
      // from the chapter's authoritative price and its story's owner.
      const chapter = await admin.entities.Chapter
        .get(mp.chapter_id)
        .catch((e) => (e.status === 404 ? null : Promise.reject(e)));
      if (!chapter) return Response.json({ error: 'Chapter not found' }, { status: 400 });
      if (chapter.status !== 'paid') return Response.json({ error: 'Chapter is not a paid chapter' }, { status: 400 });

      const story = await admin.entities.Story
        .get(chapter.story_id)
        .catch((e) => (e.status === 404 ? null : Promise.reject(e)));
      if (!story) return Response.json({ error: 'Story not found' }, { status: 400 });

      const amount = Number(chapter.price || 0);
      if (!(amount > 0)) return Response.json({ error: 'Chapter price is not set' }, { status: 400 });

      const reference = String(mp.reference || '').trim();
      if (!/^[\w.\- ]{4,64}$/.test(reference)) {
        return Response.json({ error: 'Bank transfer reference is missing or invalid' }, { status: 400 });
      }

      const feePercent = await getFeePercent(base44);
      const { writerShare, platformShare } = splitAmount(amount, feePercent);

      const existing = await admin.entities.Purchase.filter({ reader_id: mp.reader_id, chapter_id: chapter.id });
      if (!existing.length) {
        await admin.entities.Purchase.create({
          reader_id: mp.reader_id,
          chapter_id: chapter.id,
          writer_id: story.created_by_id,
          amount,
          writer_share: writerShare,
          platform_share: platformShare,
          fee_percent: feePercent,
          payment_method: 'manual',
          status: 'completed',
          stripe_payment_id: reference,
        });
      }

      await admin.entities.ManualPayment.update(mp.id, {
        status: 'approved',
        amount,
        writer_id: story.created_by_id,
      });
      return Response.json({ ok: true, amount, writer_id: story.created_by_id });
    }
    if (action === 'reject_manual') {
      await admin.entities.ManualPayment.update(payload.id, { status: 'rejected' });
      return Response.json({ ok: true });
    }
    if (action === 'mark_payout_paid') {
      await admin.entities.Payout.update(payload.id, { status: 'paid', paid_at: new Date().toISOString() });
      return Response.json({ ok: true });
    }
    if (action === 'set_fee') {
      const existing = await admin.entities.Setting.filter({ key: 'platform_fee_percent' });
      if (existing[0]) await admin.entities.Setting.update(existing[0].id, { value: String(payload.value) });
      else await admin.entities.Setting.create({ key: 'platform_fee_percent', value: String(payload.value) });
      return Response.json({ ok: true });
    }
    if (action === 'set_bank') {
      const existing = await admin.entities.Setting.filter({ key: 'bank_instructions' });
      if (existing[0]) await admin.entities.Setting.update(existing[0].id, { value: payload.value });
      else await admin.entities.Setting.create({ key: 'bank_instructions', value: payload.value });
      return Response.json({ ok: true });
    }
    if (action === 'unpublish_story') {
      await admin.entities.Story.update(payload.id, { status: 'draft' });
      return Response.json({ ok: true });
    }
    if (action === 'suspend_user') {
      await admin.entities.User.update(payload.id, { suspended: true });
      return Response.json({ ok: true });
    }
    if (action === 'reinstate_user') {
      await admin.entities.User.update(payload.id, { suspended: false });
      return Response.json({ ok: true });
    }
    if (action === 'resolve_report') {
      await admin.entities.Report.update(payload.id, { status: 'resolved' });
      return Response.json({ ok: true });
    }

    return Response.json({ error: 'Unknown action' }, { status: 400 });
  } catch (error) {
    console.error('adminAction error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/aiWritingAssistant/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to use the assistant' }, { status: 401 });

    const { action, content, selection, title } = await req.json();
    const text = (selection || content || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
    if (!text && action !== 'suggest') return Response.json({ error: 'Nothing to work with yet' }, { status: 400 });

    const prompts = {
      continue: `You are a writing assistant helping an author continue their serialized story chapter titled "${title || 'Untitled'}". Continue the narrative naturally in the author's voice and tense. Write 2-4 paragraphs of new prose that follows on from the text below. Output only the story prose — no commentary, headings, or notes.\n\nSo far:\n${text.slice(-3000)}`,
      suggest: `You are a writing assistant for a serialized story chapter titled "${title || 'Untitled'}". Suggest 3 distinct, specific directions for what could happen next, each in one sentence. Return only a numbered list with no extra commentary.\n\nContext:\n${text.slice(-2000)}`,
      rewrite: `You are a writing assistant. Rewrite the passage below to be tighter and more vivid, preserving the author's voice, tense, and point of view. Return only the rewritten passage with no commentary.\n\n${text}`,
      grammar: `You are a copy editor. Fix grammar, spelling, and clarity in the passage below while preserving the author's voice and meaning. Return only the corrected passage with no commentary or explanations.\n\n${text}`,
    };

    const prompt = prompts[action];
    if (!prompt) return Response.json({ error: 'Unknown action' }, { status: 400 });

    const result = await base44.asServiceRole.integrations.Core.InvokeLLM({ prompt });
    return Response.json({ text: typeof result === 'string' ? result : JSON.stringify(result) });
  } catch (error) {
    console.error('aiWritingAssistant error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/analyzeWriting/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to use the writing coach' }, { status: 401 });

    const { text, context } = await req.json();
    const clean = (text || '').replace(/<[^>]+>/g, ' ').replace(/&nbsp;/g, ' ').replace(/\s+/g, ' ').trim();
    if (!clean) return Response.json({ error: 'Paste some text to analyze' }, { status: 400 });

    const ctx = context ? `\nContext (story/chapter the author is working on): ${String(context).slice(0, 500)}` : '';

    const prompt = `You are an expert copy editor and writing coach in the style of Grammarly, helping a serialized-fiction author. Analyze the passage below and return a structured review.

For each issue, capture:
- type: one of "grammar", "spelling", "punctuation", "style", "clarity", "tone", "word_choice", "repetition"
- original: the exact problematic phrase from the text
- suggestion: the corrected or improved version
- explanation: a short reason for the change
- severity: "low" | "medium" | "high"

Also give four 0–100 scores (correctness, clarity, engagement, tone), a one-sentence summary, and a fully corrected version of the passage that preserves the author's voice, tense, and point of view.

Do not invent issues that are not present. If the text is already clean, return an empty issues array and high scores.${ctx}

Passage:
"""
${clean.slice(0, 4000)}
"""`;

    const result = await base44.asServiceRole.integrations.Core.InvokeLLM({
      prompt,
      response_json_schema: {
        type: 'object',
        properties: {
          scores: {
            type: 'object',
            properties: {
              correctness: { type: 'number' },
              clarity: { type: 'number' },
              engagement: { type: 'number' },
              tone: { type: 'number' },
            },
          },
          issues: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                type: { type: 'string' },
                original: { type: 'string' },
                suggestion: { type: 'string' },
                explanation: { type: 'string' },
                severity: { type: 'string' },
              },
            },
          },
          summary: { type: 'string' },
          corrected: { type: 'string' },
        },
      },
    });

    return Response.json(result);
  } catch (error) {
    console.error('analyzeWriting error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/createCheckout/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import Stripe from 'npm:stripe@17.6.0';
import { secrets } from 'base44:runtime';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to checkout' }, { status: 401 });

    const body = await req.json();
    const { type, chapterId, writerId } = body;
    const appId = secrets.get('BASE44_APP_ID');
    const origin = new URL(req.url).origin;
    const stripe = new Stripe(secrets.get('STRIPE_SECRET_KEY'));

    if (type === 'chapter') {
      const chapter = await base44.entities.Chapter.get(chapterId);
      if (!chapter) return Response.json({ error: 'Chapter not found' }, { status: 404 });
      if (chapter.status !== 'paid') return Response.json({ error: 'Chapter is free' }, { status: 400 });
      const story = await base44.entities.Story.get(chapter.story_id);
      const amount = Math.max(50, Math.round(Number(chapter.price || 0) * 100));
      const session = await stripe.checkout.sessions.create({
        mode: 'payment',
        payment_method_types: ['card'],
        line_items: [{
          price_data: {
            currency: 'usd',
            unit_amount: amount,
            product_data: { name: `${story.title} — ${chapter.title}` },
          },
          quantity: 1,
        }],
        success_url: `${origin}/read/${chapter.id}?paid=1`,
        cancel_url: `${origin}/read/${chapter.id}?paid=0`,
        metadata: {
          base44_app_id: appId,
          type: 'chapter',
          chapter_id: chapter.id,
          writer_id: story.created_by_id,
          reader_id: user.id,
          amount: String(amount),
        },
      }, { idempotencyKey: crypto.randomUUID() });
      return Response.json({ url: session.url });
    }

    if (type === 'subscription') {
      const stories = await base44.entities.Story.filter({ created_by_id: writerId, status: 'published' });
      const price = stories[0]?.subscription_price ?? 3.99;
      const amount = Math.max(50, Math.round(Number(price) * 100));
      const redirectId = chapterId || (stories[0] && stories[0].id) || '';
      const session = await stripe.checkout.sessions.create({
        mode: 'subscription',
        payment_method_types: ['card'],
        line_items: [{
          price_data: {
            currency: 'usd',
            unit_amount: amount,
            recurring: { interval: 'month' },
            product_data: { name: 'Author monthly subscription' },
          },
          quantity: 1,
        }],
        success_url: `${origin}/read/${redirectId}?subscribed=1`,
        cancel_url: `${origin}/read/${redirectId}?subscribed=0`,
        metadata: {
          base44_app_id: appId,
          type: 'subscription',
          writer_id: writerId,
          reader_id: user.id,
          price: String(amount),
        },
        subscription_data: {
          metadata: {
            base44_app_id: appId,
            type: 'subscription',
            writer_id: writerId,
            reader_id: user.id,
          },
        },
      }, { idempotencyKey: crypto.randomUUID() });
      return Response.json({ url: session.url });
    }

    if (type === 'membership') {
      const settings = await base44.asServiceRole.entities.Setting.filter({ key: 'membership_price_id' });
      const priceId = settings[0]?.value;
      if (!priceId) return Response.json({ error: 'Membership pricing not configured' }, { status: 500 });
      const session = await stripe.checkout.sessions.create({
        mode: 'subscription',
        payment_method_types: ['card'],
        line_items: [{ price: priceId, quantity: 1 }],
        success_url: `${origin}/membership?status=success`,
        cancel_url: `${origin}/membership?status=canceled`,
        metadata: {
          base44_app_id: appId,
          type: 'membership',
          reader_id: user.id,
        },
        subscription_data: {
          metadata: {
            base44_app_id: appId,
            type: 'membership',
            reader_id: user.id,
          },
        },
      }, { idempotencyKey: crypto.randomUUID() });
      return Response.json({ url: session.url });
    }

    if (type === 'tip') {
      if (!writerId) return Response.json({ error: 'Writer required' }, { status: 400 });
      const amount = Math.max(50, Math.round(Number(body.amount || 0) * 100));
      const session = await stripe.checkout.sessions.create({
        mode: 'payment',
        payment_method_types: ['card'],
        line_items: [{
          price_data: { currency: 'usd', unit_amount: amount, product_data: { name: 'Tip to a storyteller' } },
          quantity: 1,
        }],
        success_url: chapterId ? `${origin}/read/${chapterId}?tipped=1` : `${origin}/profile/${writerId}?tipped=1`,
        cancel_url: chapterId ? `${origin}/read/${chapterId}?tipped=0` : `${origin}/profile/${writerId}?tipped=0`,
        metadata: {
          base44_app_id: appId,
          type: 'tip',
          writer_id: writerId,
          reader_id: user.id,
          chapter_id: chapterId || '',
          amount: String(amount),
        },
      }, { idempotencyKey: crypto.randomUUID() });
      return Response.json({ url: session.url });
    }

    if (type === 'template') {
      const { templateId } = body;
      if (!templateId) return Response.json({ error: 'Template required' }, { status: 400 });
      const template = await base44.entities.CoverTemplate.get(templateId);
      if (!template) return Response.json({ error: 'Template not found' }, { status: 404 });
      if (template.is_free || !Number(template.price)) return Response.json({ error: 'Template is free' }, { status: 400 });
      const amount = Math.max(50, Math.round(Number(template.price) * 100));
      const creatorId = template.created_by_id;
      const session = await stripe.checkout.sessions.create({
        mode: 'payment',
        payment_method_types: ['card'],
        line_items: [{
          price_data: { currency: 'usd', unit_amount: amount, product_data: { name: `Cover template: ${template.title}` } },
          quantity: 1,
        }],
        success_url: `${origin}/studio?template=${template.id}&purchased=1`,
        cancel_url: `${origin}/studio?template=${template.id}&purchased=0`,
        metadata: {
          base44_app_id: appId,
          type: 'template',
          template_id: template.id,
          creator_id: creatorId,
          reader_id: user.id,
          amount: String(amount),
        },
      }, { idempotencyKey: crypto.randomUUID() });
      return Response.json({ url: session.url });
    }

    return Response.json({ error: 'Invalid checkout type' }, { status: 400 });
  } catch (error) {
    console.error('createCheckout error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/createSafepayCheckout/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { secrets } from 'base44:runtime';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to checkout' }, { status: 401 });

    const { chapterId } = await req.json();
    if (!chapterId) return Response.json({ error: 'Chapter required' }, { status: 400 });

    const chapter = await base44.entities.Chapter.get(chapterId);
    if (!chapter) return Response.json({ error: 'Chapter not found' }, { status: 404 });
    if (chapter.status !== 'paid') return Response.json({ error: 'Chapter is free' }, { status: 400 });
    const story = await base44.entities.Story.get(chapter.story_id);

    const apiKey = secrets.get('SAFEPAY_API_KEY');
    const secretKey = secrets.get('SAFEPAY_SECRET_KEY');
    if (!apiKey || !secretKey) return Response.json({ error: 'SafePay is not configured' }, { status: 500 });

    let env = 'sandbox';
    try {
      const envSettings = await base44.entities.Setting.filter({ key: 'safepay_env' });
      if (envSettings[0]?.value === 'production') env = 'production';
    } catch {}
    const apiHost = env === 'production' ? 'https://api.getsafepay.com' : 'https://sandbox.api.getsafepay.com';
    const embeddedBase = env === 'production' ? 'https://getsafepay.com/embedded/' : 'https://sandbox.api.getsafepay.com/embedded/';
    const origin = new URL(req.url).origin;

    const amount = Math.max(50, Math.round(Number(chapter.price || 0) * 100));

    // 1. Create a payment tracker
    const trackerRes = await fetch(`${apiHost}/order/payments/v3/`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'x-sfpy-merchant-secret': secretKey,
      },
      body: JSON.stringify({
        merchant_api_key: apiKey,
        intent: 'CYBERSOURCE',
        mode: 'payment',
        currency: 'USD',
        amount,
        metadata: {
          order_id: `${chapter.id}|${user.id}|${story.created_by_id}|${Number(chapter.price || 0)}`,
          source: 'chapterly',
        },
      }),
    });
    const trackerJson = await trackerRes.json();
    if (!trackerRes.ok) {
      console.error('SafePay tracker error:', JSON.stringify(trackerJson));
      return Response.json({ error: trackerJson?.status?.message || 'Failed to create payment session' }, { status: 502 });
    }
    const tracker = trackerJson?.data?.tracker?.token;
    if (!tracker) return Response.json({ error: 'No tracker returned by SafePay' }, { status: 502 });

    // 2. Generate a client auth token (tbt)
    const passRes = await fetch(`${apiHost}/client/passport/v1/token`, {
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'x-sfpy-merchant-secret': secretKey,
      },
    });
    const passJson = await passRes.json();
    if (!passRes.ok) {
      console.error('SafePay passport error:', JSON.stringify(passJson));
      return Response.json({ error: passJson?.status?.message || 'Failed to authenticate with SafePay' }, { status: 502 });
    }
    const tbt = (passJson?.data && typeof passJson.data === 'object' && passJson.data.token) ? passJson.data.token : passJson?.data;
    if (!tbt || typeof tbt !== 'string') return Response.json({ error: 'No auth token returned by SafePay' }, { status: 502 });

    // 3. Build the hosted checkout URL
    const redirect_url = `${origin}/read/${chapter.id}?safepay=1`;
    const cancel_url = `${origin}/read/${chapter.id}?safepay=0`;
    const url = `${embeddedBase}?environment=${encodeURIComponent(env)}&tbt=${encodeURIComponent(tbt)}&tracker=${encodeURIComponent(tracker)}&source=hosted&redirect_url=${encodeURIComponent(redirect_url)}&cancel_url=${encodeURIComponent(cancel_url)}`;

    return Response.json({ url });
  } catch (error) {
    console.error('createSafepayCheckout error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/deleteAccount/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Authentication required' }, { status: 401 });

    const admin = base44.asServiceRole;

    // Clean up the user's data before removing the account
    await admin.entities.Follow.deleteMany({ $or: [{ follower_id: user.id }, { writer_id: user.id }] }).catch(() => {});
    await admin.entities.Like.deleteMany({ user_id: user.id }).catch(() => {});
    await admin.entities.Comment.deleteMany({ user_id: user.id }).catch(() => {});
    await admin.entities.ReadingList.deleteMany({ user_id: user.id }).catch(() => {});
    await admin.entities.Rating.deleteMany({ user_id: user.id }).catch(() => {});
    await admin.entities.Notification.deleteMany({ user_id: user.id }).catch(() => {});
    await admin.entities.ManualPayment.deleteMany({ reader_id: user.id }).catch(() => {});
    await admin.entities.WordCountLog.deleteMany({ user_id: user.id }).catch(() => {});

    // Delete the user's stories and their chapters
    const stories = await admin.entities.Story.filter({ created_by_id: user.id }).catch(() => []);
    for (const s of stories) {
      await admin.entities.Chapter.deleteMany({ story_id: s.id }).catch(() => {});
      await admin.entities.Story.delete(s.id).catch(() => {});
    }

    // Finally remove the account record
    await admin.entities.User.delete(user.id).catch(() => {});

    return Response.json({ ok: true });
  } catch (error) {
    console.error('deleteAccount error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/generateCoverArt/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.44';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to generate cover art' }, { status: 401 });

    const { prompt, style } = await req.json();
    const p = (prompt || '').trim();
    if (!p) return Response.json({ error: 'Describe the cover art you want' }, { status: 400 });
    if (p.length > 600) return Response.json({ error: 'Prompt is too long' }, { status: 400 });

    const styled = style ? `${p}. Visual style: ${style}.` : p;
    const result = await base44.asServiceRole.integrations.Core.GenerateImage({
      prompt: `Book cover illustration, no text, no typography, no letters. ${styled}`,
    });

    return Response.json({ url: result.url });
  } catch (error) {
    console.error('generateCoverArt error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/getChapterContent/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.54';

// Returns a chapter body only to callers who are entitled to it.
// Paid chapter bodies are stored in ChapterContent (creator/admin readable only);
// free chapters keep their body on the publicly readable Chapter record.
export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me().catch((e) => (e.status === 401 ? null : Promise.reject(e)));

    const { chapterId } = await req.json().catch(() => ({}));
    if (!chapterId) return Response.json({ error: 'chapterId is required' }, { status: 400 });

    const admin = base44.asServiceRole;
    const chapter = await admin.entities.Chapter
      .get(chapterId)
      .catch((e) => (e.status === 404 ? null : Promise.reject(e)));
    if (!chapter) return Response.json({ error: 'Chapter not found' }, { status: 404 });

    const isPrivileged = !!user && (chapter.created_by_id === user.id || user.role === 'admin');
    if (!chapter.published && !isPrivileged) {
      return Response.json({ error: 'Chapter is not published' }, { status: 403 });
    }

    const meta = {
      id: chapter.id,
      title: chapter.title,
      price: Number(chapter.price || 0),
      word_count: Number(chapter.word_count || 0),
      status: chapter.status,
    };

    const readBody = async () => {
      const rows = await admin.entities.ChapterContent.filter({ chapter_id: chapter.id });
      return rows[0]?.body ?? chapter.body ?? '';
    };

    if (chapter.status !== 'paid' || isPrivileged) {
      return Response.json({ ...meta, locked: false, body: await readBody() });
    }

    if (!user) return Response.json({ ...meta, locked: true });

    // Entitlement: an unlock purchase, a platform membership, or an active subscription to this writer.
    const [purchases, memberships] = await Promise.all([
      admin.entities.Purchase.filter({ reader_id: user.id, chapter_id: chapter.id, status: 'completed' }),
      admin.entities.Subscription.filter({ reader_id: user.id, type: 'membership', status: 'active' }),
    ]);
    if (purchases.length || memberships.length) {
      return Response.json({ ...meta, locked: false, body: await readBody() });
    }

    const story = await admin.entities.Story
      .get(chapter.story_id)
      .catch((e) => (e.status === 404 ? null : Promise.reject(e)));
    if (story) {
      const subs = await admin.entities.Subscription.filter({
        reader_id: user.id,
        writer_id: story.created_by_id,
        status: 'active',
      });
      if (subs.length) return Response.json({ ...meta, locked: false, body: await readBody() });
    }

    return Response.json({ ...meta, locked: true });
  } catch (error) {
    console.error('getChapterContent error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/getMarketingKpis/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.44';
import { secrets } from 'base44:runtime';

const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
const WEEKS = 10;

async function fetchTimeseries(apiKey, appId, eventName) {
  const now = Date.now();
  const start = now - WEEKS * WEEK_MS;
  const res = await fetch(`https://app.base44.com/api/apps/${appId}/analytics/timeseries`, {
    method: 'POST',
    headers: { api_key: apiKey, 'Content-Type': 'application/json' },
    body: JSON.stringify({
      event_name: eventName,
      start_time: new Date(start).toISOString(),
      end_time: new Date(now).toISOString(),
      bucket_size_ms: WEEK_MS,
      max_buckets: WEEKS + 2,
      metrics: [{ function: 'count', name: 'count' }]
    })
  });
  if (!res.ok) {
    const text = await res.text();
    throw new Error(`Analytics API ${res.status}: ${text}`);
  }
  const data = await res.json();
  return data.buckets || [];
}

function buildKpi(label, buckets, target) {
  const series = buckets.map((b) => ({ week: b.bucket, value: b.metrics?.count || 0 }));
  const current = series.length ? series[series.length - 1].value : 0;
  const previous = series.length > 1 ? series[series.length - 2].value : 0;
  const change = previous === 0 ? (current > 0 ? 100 : 0) : Math.round(((current - previous) / previous) * 100);
  return { label, current, previous, change, target, series };
}

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
    if (user.role !== 'admin') return Response.json({ error: 'Forbidden' }, { status: 403 });

    const apiKey = secrets.get('BASE44_API_KEY');
    const appId = secrets.get('BASE44_APP_ID');
    if (!apiKey) return Response.json({ error: 'BASE44_API_KEY secret not set' }, { status: 500 });

    const [reads, signups, paid] = await Promise.all([
      fetchTimeseries(apiKey, appId, 'chapter_read'),
      fetchTimeseries(apiKey, appId, 'writer_registered'),
      fetchTimeseries(apiKey, appId, 'payment_completed')
    ]);

    return Response.json({
      kpis: [
        buildKpi('Weekly Story Reads', reads, 500),
        buildKpi('New Writer Signups', signups, 15),
        buildKpi('Weekly Paid Conversions', paid, 20)
      ]
    });
  } catch (error) {
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/getPublicProfiles/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.54';

const PUBLIC_FIELDS = ['id', 'display_name', 'full_name', 'avatar_url', 'bio'];

export default async function (req: Request): Promise<Response> {
  try {
    const { userIds } = await req.json().catch(() => ({}));
    const ids = Array.isArray(userIds)
      ? [...new Set(userIds.filter((v) => typeof v === 'string' && /^[0-9a-f]{24}$/i.test(v)))].slice(0, 50)
      : [];
    if (!ids.length) return Response.json({ profiles: [] });

    const base44 = createClientFromRequest(req);
    // Deliberately public identity for a publishing platform: names, avatars and bios only.
    // No email, role, or banking fields ever leave the server.
    // No options object: the paged form is not available on the User entity.
    const found = await base44.asServiceRole.entities.User.filter({ id: { $in: ids } });

    const profiles = (found || []).slice(0, 50).map((u: Record<string, unknown>) => {
      const profile: Record<string, unknown> = {};
      for (const field of PUBLIC_FIELDS) profile[field] = u[field] ?? null;
      return profile;
    });

    return Response.json({ profiles });
  } catch (error) {
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/getWeeklyLeaderboard/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

const WEEK_MS = 7 * 24 * 60 * 60 * 1000;

export default async function(req: Request) {
  try {
    const base44 = createClientFromRequest(req);

    // Signed-in only: this aggregates every user's tips and comments through the
    // service role, so it must not be readable by anyone on the internet.
    const user = await base44.auth.me().catch((e: any) => (e?.status === 401 ? null : Promise.reject(e)));
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });

    const since = new Date(Date.now() - WEEK_MS).toISOString();
    const [tips, comments] = await Promise.all([
      base44.asServiceRole.entities.Tip.filter({ created_date: { $gte: since } }),
      base44.asServiceRole.entities.Comment.filter({ created_date: { $gte: since } }),
    ]);

    // Most active readers: tips given + comments posted this week
    const readerMap: Record<string, any> = {};
    for (const t of tips) {
      if (!t.reader_id) continue;
      (readerMap[t.reader_id] ||= { id: t.reader_id, tips: 0, tipAmount: 0, comments: 0 });
      readerMap[t.reader_id].tips++;
      readerMap[t.reader_id].tipAmount += t.amount || 0;
    }
    for (const c of comments) {
      if (!c.user_id) continue;
      (readerMap[c.user_id] ||= { id: c.user_id, tips: 0, tipAmount: 0, comments: 0 });
      readerMap[c.user_id].comments++;
    }
    const readerList = Object.values(readerMap).map((r: any) => ({ ...r, score: r.tips + r.comments }));
    readerList.sort((a: any, b: any) => b.score - a.score);
    const topReaders = readerList.slice(0, 5);

    // Top contributors: writers who received the most tips this week
    const writerMap: Record<string, any> = {};
    for (const t of tips) {
      if (!t.writer_id) continue;
      (writerMap[t.writer_id] ||= { id: t.writer_id, tips: 0, amount: 0 });
      writerMap[t.writer_id].tips++;
      writerMap[t.writer_id].amount += t.amount || 0;
    }
    const writerList = Object.values(writerMap);
    writerList.sort((a: any, b: any) => b.amount - a.amount);
    const topWriters = writerList.slice(0, 5);

    // Resolve user display info
    const ids = [...new Set([...topReaders.map((r: any) => r.id), ...topWriters.map((w: any) => w.id)])];
    const users: Record<string, any> = {};
    if (ids.length) {
      const rows = await base44.asServiceRole.entities.User.filter({ id: { $in: ids } });
      for (const u of rows) users[u.id] = u;
    }
    const pick = (u: any) => u
      ? { name: u.display_name || u.full_name || 'Anonymous', avatar_url: u.avatar_url || null }
      : { name: 'Anonymous', avatar_url: null };

    return Response.json({
      readers: topReaders.map((r: any) => ({ ...r, ...pick(users[r.id]) })),
      contributors: topWriters.map((w: any) => ({ ...w, ...pick(users[w.id]) })),
    });
  } catch (error) {
    console.error('getWeeklyLeaderboard error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/importStoryFromDocument/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

const RESPONSE_SCHEMA = {
  type: 'object',
  properties: {
    title: { type: 'string' },
    description: { type: 'string' },
    chapters: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          title: { type: 'string' },
          body: { type: 'string' },
        },
        required: ['title', 'body'],
      },
    },
  },
  required: ['title', 'chapters'],
};

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await req.json();
    const fileUrl = body?.file_url;
    if (!fileUrl || typeof fileUrl !== 'string') {
      return Response.json({ error: 'file_url is required' }, { status: 400 });
    }

    const prompt = `You are given a document that contains a serialized fiction story (a single chapter or many chapters). Split it into chapters and return structured data.

Rules:
- Identify the story title from the document title or first heading; if unclear, use "Untitled Story".
- Write a one-sentence description drawn from the opening.
- Split into chapters at natural boundaries (chapter headings, "Chapter X", numbered sections, or major scene breaks). If there are no clear markers, treat the whole document as one chapter titled "Chapter 1".
- For each chapter body, return the FULL text as HTML: wrap each paragraph in <p>...</p>. Do not summarize, abbreviate, or truncate — include the complete original wording.
- Preserve chapter order.

Return JSON matching the schema.`;

    const result = await base44.asServiceRole.integrations.Core.InvokeLLM({
      prompt,
      file_urls: [fileUrl],
      response_json_schema: RESPONSE_SCHEMA,
    });

    return Response.json(result);
  } catch (error) {
    console.error('importStoryFromDocument error', error);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/incrementChapterView/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { getRateLimitIdentity, isRateLimited } from '../../shared/chapterViewGuard.ts';

export default async function(req: Request) {
  try {
    const body = await req.json().catch(() => ({}));
    const chapterId = body?.chapterId;
    if (!chapterId || typeof chapterId !== 'string') {
      return Response.json({ error: 'chapterId required' }, { status: 400 });
    }

    const base44 = createClientFromRequest(req);

    // Rate limiting is keyed on the signed-in reader (falling back to the
    // platform-set connection IP), never on spoofable Origin/Referer headers.
    const user = await base44.auth.me().catch(() => null);
    const identity = getRateLimitIdentity(user?.id || null, req);
    if (isRateLimited(identity, chapterId, 'view')) {
      return Response.json({ ok: true, rate_limited: true });
    }
    const chapters = await base44.asServiceRole.entities.Chapter.filter({ id: chapterId });
    if (!chapters || chapters.length === 0) {
      return Response.json({ error: 'Chapter not found' }, { status: 404 });
    }
    if (!chapters[0].published) {
      return Response.json({ ok: true, skipped: true });
    }

    await base44.asServiceRole.entities.Chapter.updateMany({ id: chapterId }, { $inc: { views: 1 } });
    return Response.json({ ok: true });
  } catch (error) {
    console.error('incrementChapterView error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/logChapterCompletion/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { getRateLimitIdentity, isRateLimited } from '../../shared/chapterViewGuard.ts';

export default async function(req: Request) {
  try {
    const body = await req.json().catch(() => ({}));
    const chapterId = body?.chapterId;
    if (!chapterId || typeof chapterId !== 'string') {
      return Response.json({ error: 'chapterId required' }, { status: 400 });
    }

    const base44 = createClientFromRequest(req);

    // Rate limiting is keyed on the signed-in reader (falling back to the
    // platform-set connection IP), never on spoofable Origin/Referer headers.
    const user = await base44.auth.me().catch(() => null);
    const identity = getRateLimitIdentity(user?.id || null, req);
    if (isRateLimited(identity, chapterId, 'complete')) {
      return Response.json({ ok: true, rate_limited: true });
    }
    const chapters = await base44.asServiceRole.entities.Chapter.filter({ id: chapterId });
    if (!chapters || chapters.length === 0) {
      return Response.json({ error: 'Chapter not found' }, { status: 404 });
    }
    if (!chapters[0].published) {
      return Response.json({ ok: true, skipped: true });
    }

    await base44.asServiceRole.entities.Chapter.updateMany({ id: chapterId }, { $inc: { full_reads: 1 } });
    return Response.json({ ok: true });
  } catch (error) {
    console.error('logChapterCompletion error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/logDailyWordCount/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

const todayUTC = () => new Date().toISOString().slice(0, 10);

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });

    const stories = await base44.entities.Story.filter({ created_by_id: user.id });
    let total = 0;
    for (const s of stories) {
      const chapters = await base44.entities.Chapter.filter({ story_id: s.id });
      for (const c of chapters) total += c.word_count || 0;
    }

    const today = todayUTC();
    const existing = await base44.entities.WordCountLog.filter({ created_by_id: user.id, date: today });
    if (existing.length > 0) {
      await base44.entities.WordCountLog.update(existing[0].id, { words: total });
    } else {
      await base44.entities.WordCountLog.create({ user_id: user.id, date: today, words: total });
    }

    return Response.json({ date: today, words: total, logged: true });
  } catch (error) {
    console.error('logDailyWordCount error', error);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/notifyCitation/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { escapeHtml } from '../../shared/emailSafeText.ts';

// Workflow-triggered: fires when a Citation record is created (see the
// "Citation Notification" workflow). Notifies the cited paper's author via
// dashboard notification + email so they can see who is building on their work.
export default async function (req: Request): Promise<Response> {
  try {
    const base44 = createClientFromRequest(req);

    // Workflow-only notifier (the Citation Notification workflow runs as its
    // admin owner). Requiring an admin caller stops anyone on the internet
    // from firing notifications/emails from arbitrary citation ids.
    const user = await base44.auth.me().catch((e: any) => (e?.status === 401 ? null : Promise.reject(e)));
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
    if (user.role !== 'admin') return Response.json({ error: 'Forbidden' }, { status: 403 });

    const body = await req.json().catch(() => ({}));
    const citingPaperId = body.citing_paper_id;
    const citedPaperId = body.cited_paper_id;
    if (!citingPaperId || !citedPaperId) {
      return Response.json({ error: 'citing_paper_id and cited_paper_id required' }, { status: 400 });
    }

    // Ground the alert in a real citation record.
    const citationRecords = await base44.asServiceRole.entities.Citation.filter({
      citing_paper_id: citingPaperId,
      cited_paper_id: citedPaperId,
    });
    if (!citationRecords || !citationRecords.length) {
      return Response.json({ skipped: true, reason: 'citation record not found' });
    }

    const citedPaper = await base44.asServiceRole.entities.ResearchPaper.get(citedPaperId).catch(() => null);
    if (!citedPaper) return Response.json({ skipped: true, reason: 'cited paper not found' });

    const citingPaper = await base44.asServiceRole.entities.ResearchPaper.get(citingPaperId).catch(() => null);
    if (!citingPaper) return Response.json({ skipped: true, reason: 'citing paper not found' });

    // Don't notify authors for self-citations.
    if (citedPaper.created_by_id === citingPaper.created_by_id) {
      return Response.json({ skipped: true, reason: 'self-citation' });
    }

    // Idempotency: one notification per (author, citing paper) — avoids duplicate
    // alerts when a paper is re-published (references are reconciled each publish).
    const existing = await base44.asServiceRole.entities.Notification.filter({
      user_id: citedPaper.created_by_id,
      type: 'citation',
      target_id: citingPaperId,
    });
    if (existing && existing.length) {
      return Response.json({ skipped: true, reason: 'already notified' });
    }

    const citingAuthors = (citingPaper.authors || []).join(', ') || 'A researcher';
    const bodyText = `New citation: "${citingPaper.title}" by ${citingAuthors} cited your paper "${citedPaper.title}".`;

    await base44.asServiceRole.entities.Notification.create({
      user_id: citedPaper.created_by_id,
      type: 'citation',
      body: bodyText,
      target_id: citingPaperId,
      read: false,
    });

    // Email the cited author (they are a registered user who published the paper).
    const author = await base44.asServiceRole.entities.User.get(citedPaper.created_by_id).catch(() => null);
    let emailed = false;
    if (author && author.email) {
      try {
        await base44.asServiceRole.integrations.Core.SendEmail({
          to: author.email,
          subject: 'Your paper was cited on Chapterly',
          body: `Hi ${escapeHtml(author.display_name || author.full_name || 'there')},\n\n"${escapeHtml(citingPaper.title)}" by ${escapeHtml(citingAuthors)} just cited your paper "${escapeHtml(citedPaper.title)}".\n\nOpen Chapterly to see who's building on your work.\n\n— The Chapterly team`,
        });
        emailed = true;
      } catch (e) {
        console.error('notifyCitation email failed', e);
      }
    }

    return Response.json({ notified: true, emailed });
  } catch (error) {
    console.error('notifyCitation error', error);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/notifyMentions/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { escapeHtml } from '../../shared/emailSafeText.ts';

// Workflow-triggered: fires when a paper, story, chapter, or comment is
// published/created (see the * Mention Notification workflows). Scans the
// source content for mentions of published research papers — by direct link,
// by title in text, or by reference-list entry — and emails each mentioned
// paper's author so they can track their impact.
const TITLE_MIN_LEN = 20;

function norm(s) {
  return (s || '').toString().toLowerCase().replace(/\s+/g, ' ').trim();
}

export default async function (req: Request): Promise<Response> {
  try {
    const base44 = createClientFromRequest(req);

    // Only the * Mention Notification workflows call this (they run as the app
    // admin who owns them). Requiring an admin caller stops anyone on the
    // internet from fabricating mentions/emails from arbitrary source ids.
    const user = await base44.auth.me().catch((e: any) => (e?.status === 401 ? null : Promise.reject(e)));
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
    if (user.role !== 'admin') return Response.json({ error: 'Forbidden' }, { status: 403 });

    const body = await req.json().catch(() => ({}));
    const sourceType = body.source_type;
    const sourceId = body.source_id;
    if (!sourceType || !sourceId) {
      return Response.json({ error: 'source_type and source_id required' }, { status: 400 });
    }

    // Fetch the source record and build the text haystack + routing info.
    let source: any = null;
    let haystack = '';
    let sourceTitle = '';
    let sourceAuthorId: string | null = null;
    let references: any[] = [];
    let notifTargetId = sourceId;

    if (sourceType === 'paper') {
      source = await base44.asServiceRole.entities.ResearchPaper.get(sourceId).catch(() => null);
      if (!source || source.status !== 'published') return Response.json({ skipped: true, reason: 'paper not published' });
      haystack = [source.body, source.abstract, source.title].join(' ');
      sourceTitle = source.title;
      sourceAuthorId = source.created_by_id;
      references = source.references || [];
    } else if (sourceType === 'story') {
      source = await base44.asServiceRole.entities.Story.get(sourceId).catch(() => null);
      if (!source || source.status !== 'published') return Response.json({ skipped: true, reason: 'story not published' });
      haystack = [source.description, source.title, (source.tags || []).join(' ')].join(' ');
      sourceTitle = source.title;
      sourceAuthorId = source.created_by_id;
    } else if (sourceType === 'chapter') {
      source = await base44.asServiceRole.entities.Chapter.get(sourceId).catch(() => null);
      if (!source || !source.published) return Response.json({ skipped: true, reason: 'chapter not published' });
      haystack = [source.body, source.title].join(' ');
      sourceTitle = source.title;
      sourceAuthorId = source.created_by_id;
    } else if (sourceType === 'comment') {
      source = await base44.asServiceRole.entities.Comment.get(sourceId).catch(() => null);
      if (!source) return Response.json({ skipped: true, reason: 'comment not found' });
      haystack = source.body || '';
      sourceAuthorId = source.user_id || source.created_by_id;
      if (source.chapter_id) {
        const ch = await base44.asServiceRole.entities.Chapter.get(source.chapter_id).catch(() => null);
        sourceTitle = ch ? ch.title : 'a comment';
        notifTargetId = source.chapter_id;
      } else {
        sourceTitle = 'a comment';
      }
    } else {
      return Response.json({ error: 'invalid source_type' }, { status: 400 });
    }

    const normHay = norm(haystack);
    if (!normHay) return Response.json({ skipped: true, reason: 'empty content' });

    const papers = await base44.asServiceRole.entities.ResearchPaper.filter({ status: 'published' }, '-created_date', 200);
    if (!papers || !papers.length) return Response.json({ notified: 0 });

    // Dedup: mentions already recorded for this source.
    const existingMentions = await base44.asServiceRole.entities.Mention.filter({ source_type: sourceType, source_id: sourceId });
    const mentionedIds = new Set((existingMentions || []).map((m: any) => m.paper_id));

    // For paper sources, skip targets that are already formally cited (the
    // citation workflow emails those authors separately).
    const citedIds = new Set<string>();
    if (sourceType === 'paper') {
      const cites = await base44.asServiceRole.entities.Citation.filter({ citing_paper_id: sourceId });
      (cites || []).forEach((c: any) => citedIds.add(c.cited_paper_id));
    }

    const sourceLabel =
      sourceType === 'paper' ? `the paper "${sourceTitle}"` :
      sourceType === 'story' ? `the story "${sourceTitle}"` :
      sourceType === 'chapter' ? `the chapter "${sourceTitle}"` :
      `a comment on "${sourceTitle}"`;

    let notified = 0;
    for (const paper of papers) {
      if (paper.created_by_id === sourceAuthorId) continue; // no self-mention spam
      if (mentionedIds.has(paper.id)) continue;
      if (citedIds.has(paper.id)) continue;

      const cid = paper.citation_id || '';
      let matched = false;

      // Direct link / citation-id match in text.
      if (normHay.includes(`/research/${paper.id}`) || (cid && normHay.includes(norm(cid)))) {
        matched = true;
      }

      // Title-in-text match (only for sufficiently specific titles).
      if (!matched) {
        const t = norm(paper.title);
        if (t.length >= TITLE_MIN_LEN && normHay.includes(t)) matched = true;
      }

      // Reference-list match (paper source only): external reference whose
      // title equals the paper's title or whose url points at it.
      if (!matched && sourceType === 'paper') {
        for (const ref of references) {
          if (!ref || ref.paper_id) continue; // formal citation, handled separately
          const rt = norm(ref.title);
          if (rt && rt.length >= TITLE_MIN_LEN && rt === norm(paper.title)) { matched = true; break; }
          const ru = (ref.url || '').toLowerCase();
          if (ru && (ru.includes(paper.id) || (cid && ru.includes(cid.toLowerCase())))) { matched = true; break; }
        }
      }

      if (!matched) continue;

      await base44.asServiceRole.entities.Mention.create({
        source_type: sourceType,
        source_id: sourceId,
        paper_id: paper.id,
      }).catch(() => {});

      await base44.asServiceRole.entities.Notification.create({
        user_id: paper.created_by_id,
        type: 'mention',
        body: `Your paper "${paper.title}" was mentioned in ${sourceLabel}.`,
        target_id: notifTargetId,
        source_type: sourceType,
        read: false,
      }).catch((e: any) => console.error('mention notification failed', e));

      const author = await base44.asServiceRole.entities.User.get(paper.created_by_id).catch(() => null);
      if (author && author.email) {
        try {
          await base44.asServiceRole.integrations.Core.SendEmail({
            to: author.email,
            subject: 'Your paper was mentioned on Chapterly',
            body: `Hi ${escapeHtml(author.display_name || author.full_name || 'there')},\n\nYour paper "${escapeHtml(paper.title)}" was just mentioned in ${escapeHtml(sourceLabel)}.\n\nOpen Chapterly to see who's building on your work.\n\n— The Chapterly team`,
          });
        } catch (e) {
          console.error('mention email failed', e);
        }
      }
      notified++;
    }

    return Response.json({ notified });
  } catch (error) {
    console.error('notifyMentions error', error);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/notifyNewChapter/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { escapeHtml, toPlainText } from '../../shared/emailSafeText.ts';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);

    // Authenticate the caller
    let user;
    try {
      user = await base44.auth.me();
    } catch {
      return Response.json({ error: 'Authentication required' }, { status: 401 });
    }
    if (!user) {
      return Response.json({ error: 'Authentication required' }, { status: 401 });
    }

    let body = {};
    try { body = await req.json(); } catch {}
    const chapterId = body.chapter_id;
    if (!chapterId) return Response.json({ error: 'chapter_id required' }, { status: 400 });

    const chapter = await base44.asServiceRole.entities.Chapter.get(chapterId);
    if (!chapter || !chapter.published) {
      return Response.json({ skipped: true, reason: 'not published' });
    }

    const story = await base44.asServiceRole.entities.Story.get(chapter.story_id);

    // Verify the caller is the story author or an admin
    const isAuthor = story && story.created_by_id === user.id;
    const isAdmin = user.role === 'admin';
    if (!isAuthor && !isAdmin) {
      return Response.json({ error: 'Only the author can trigger chapter notifications' }, { status: 403 });
    }

    // Idempotency: don't notify twice for the same chapter
    const existing = await base44.asServiceRole.entities.Notification.filter(
      { type: 'new_chapter', target_id: chapterId }
    );
    if (existing.length) {
      return Response.json({ skipped: true, reason: 'already notified', count: existing.length });
    }
    const writer = await base44.asServiceRole.entities.User.get(story.created_by_id);
    const writerName = writer?.display_name || writer?.full_name || 'A writer';
    const followers = await base44.asServiceRole.entities.Follow.filter({ writer_id: story.created_by_id });
    if (!followers.length) return Response.json({ notified: 0, emailed: 0 });

    // Dashboard notifications for every follower
    await base44.asServiceRole.entities.Notification.bulkCreate(
      followers.map((f) => ({
        user_id: f.follower_id,
        type: 'new_chapter',
        body: `New chapter "${chapter.title}" from ${writerName}`,
        target_id: chapterId,
        read: false,
      }))
    );

    // Email notifications (followers are registered users)
    const followerUsers = await Promise.all(
      followers.map((f) => base44.asServiceRole.entities.User.get(f.follower_id).catch(() => null))
    );
    const emailResults = await Promise.allSettled(
      followerUsers
        .filter((u) => u && u.email)
        .map((u) =>
          base44.asServiceRole.integrations.Core.SendEmail({
            to: u.email,
            subject: `New chapter: ${toPlainText(chapter.title)}`,
            body: `Hi ${escapeHtml(u.display_name || u.full_name || 'there')},\n\n${escapeHtml(writerName)} just published a new chapter "${escapeHtml(chapter.title)}" in "${escapeHtml(story.title)}".\n\nOpen Chapterly to read it now.\n\n— The Chapterly team`,
          })
        )
    );
    const emailed = emailResults.filter((r) => r.status === 'fulfilled').length;

    return Response.json({ notified: followers.length, emailed });
  } catch (error) {
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/notifyPayoutEmail/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.44';
import { notifySlack } from '../../shared/slackNotify.ts';

function base64UrlEncode(str) {
  const bytes = new TextEncoder().encode(str);
  let bin = '';
  bytes.forEach((b) => (bin += String.fromCharCode(b)));
  return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

function buildMessage(to, from, subject, body) {
  return [
    `From: ${from}`,
    `To: ${to}`,
    `Subject: ${subject}`,
    'MIME-Version: 1.0',
    'Content-Type: text/plain; charset=UTF-8',
    '',
    body,
  ].join('\r\n');
}

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);

    // Workflow-only (Payout Email Notification runs as the app admin). Requiring
    // an admin caller stops anonymous replays of this send path.
    const user = await base44.auth.me().catch((e: any) => (e?.status === 401 ? null : Promise.reject(e)));
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
    if (user.role !== 'admin') return Response.json({ error: 'Forbidden' }, { status: 403 });

    const { payout_id } = await req.json();
    if (!payout_id) return Response.json({ error: 'payout_id required' }, { status: 400 });

    let payout;
    try {
      payout = await base44.asServiceRole.entities.Payout.get(payout_id);
    } catch (e) {
      return Response.json({ skipped: true, reason: 'payout not found' });
    }
    if (!payout || payout.status !== 'paid') {
      return Response.json({ skipped: true, reason: 'payout not paid' });
    }

    // One-shot: never email the same payout twice.
    if (payout.notification_sent) {
      return Response.json({ skipped: true, reason: 'already notified' });
    }

    const writer = await base44.asServiceRole.entities.User.get(payout.writer_id);
    if (!writer || !writer.email) {
      console.error('notifyPayoutEmail: writer missing or no email');
      return Response.json({ skipped: true, reason: 'no writer email' });
    }

    const { accessToken } = await base44.asServiceRole.connectors.getConnection('gmail');

    // Resolve the sender (builder) Gmail address for a friendly From header
    let fromAddr = '';
    try {
      const profileRes = await fetch('https://gmail.googleapis.com/gmail/v1/users/me/profile', {
        headers: { Authorization: `Bearer ${accessToken}` },
      });
      if (profileRes.ok) {
        const profile = await profileRes.json();
        fromAddr = profile.emailAddress || '';
      }
    } catch (e) {
      console.error('notifyPayoutEmail: profile fetch failed', e.message);
    }
    const from = `Chapterly <${fromAddr || 'me'}>`;

    const amount = Number(payout.amount || 0).toFixed(2);
    const method = payout.method || 'payout';
    const ref = payout.reference || '';
    const paidAt = payout.paid_at
      ? new Date(payout.paid_at).toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' })
      : new Date().toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' });
    const firstName = (writer.full_name || 'there').split(' ')[0];

    const subject = `Your Chapterly payout of $${amount} has been sent`;
    const body =
      `Hi ${firstName},\n\n` +
      `Great news — your payout of $${amount} via ${method} has been processed` +
      `${ref ? ` (reference: ${ref})` : ''} as of ${paidAt}.\n\n` +
      `It should arrive in your account within a few business days, depending on your payout method.\n\n` +
      `Thanks for writing on Chapterly — keep the stories coming.\n\n` +
      `— The Chapterly team`;

    await notifySlack(base44, `💸 Payout of $${amount} sent to ${firstName} via ${method}${ref ? ` (ref: ${ref})` : ''}.`);

    const raw = base64UrlEncode(buildMessage(writer.email, from, subject, body));

    const sendRes = await fetch('https://gmail.googleapis.com/gmail/v1/users/me/messages/send', {
      method: 'POST',
      headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json' },
      body: JSON.stringify({ raw }),
    });

    if (!sendRes.ok) {
      const err = await sendRes.text();
      console.error('notifyPayoutEmail: gmail send failed', err);
      return Response.json({ error: 'gmail send failed' }, { status: 502 });
    }

    const result = await sendRes.json();

    // Record the send so a repeated trigger cannot replay the email.
    await base44.asServiceRole.entities.Payout.update(payout.id, { notification_sent: true })
      .catch((e) => console.error('notifyPayoutEmail: could not record notification_sent', e.message));

    return Response.json({ sent: true, message_id: result.id });
  } catch (error) {
    console.error('notifyPayoutEmail error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/postComment/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

// Agent-invoked: posts a comment on a chapter as the authenticated reader.
// Runs as the app user so the Comment RLS (user_id == user.id) is satisfied.
export default async function (req: Request): Promise<Response> {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to comment' }, { status: 401 });

    const body = await req.json().catch(() => ({}));
    const { chapterId, body: text } = body;
    if (!chapterId || !text || !String(text).trim()) {
      return Response.json({ error: 'chapterId and body required' }, { status: 400 });
    }

    const chapter = await base44.entities.Chapter.get(chapterId).catch(() => null);
    if (!chapter) return Response.json({ error: 'Chapter not found' }, { status: 404 });

    const comment = await base44.entities.Comment.create({
      chapter_id: chapterId,
      user_id: user.id,
      body: String(text).trim(),
    });

    return Response.json({ id: comment.id, created: true });
  } catch (error) {
    console.error('postComment error', error);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/postMyStoryToInstagram/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.44';
import { publishStoryToInstagram } from '../../shared/instagramPublish.ts';

// Per-writer function: posts one of the writer's own stories to their own
// Instagram Business account via the app-user "Writer Instagram" connector.
const CONNECTOR_ID = '6a915ab0a8d4e91b72704571';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await req.json().catch(() => ({}));
    const { story_id, dry_run } = body;
    if (!story_id) return Response.json({ error: 'story_id required' }, { status: 400 });

    const story = await base44.asServiceRole.entities.Story.get(story_id);
    if (!story) return Response.json({ error: 'story not found' }, { status: 404 });
    if (story.created_by_id !== user.id && user.role !== 'admin') {
      return Response.json({ error: 'You can only post your own stories' }, { status: 403 });
    }
    if (!story.cover_url) return Response.json({ error: 'Story has no cover image' }, { status: 400 });

    if (dry_run) return Response.json({ dry_run: true, story: { id: story.id, title: story.title } });

    const { accessToken } = await base44.asServiceRole.connectors.getCurrentAppUserConnection(CONNECTOR_ID);
    const siteSetting = (await base44.asServiceRole.entities.Setting.filter({ key: 'public_site_url' }))[0];
    const siteUrl = siteSetting?.value || '';

    const result = await publishStoryToInstagram(base44, {
      accessToken,
      story,
      scope: 'writer',
      writerId: user.id,
      siteUrl,
    });
    return Response.json({ success: true, story_id: story.id, ...result });
  } catch (error) {
    console.error('postMyStoryToInstagram error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/publishResearchPaper/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

export default async function (req: Request): Promise<Response> {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });

    const body = await req.json().catch(() => ({}));
    const paperId = body.paperId;
    if (!paperId) return Response.json({ error: 'paperId required' }, { status: 400 });

    const paper = await base44.entities.ResearchPaper.get(paperId);
    if (!paper) return Response.json({ error: 'Paper not found' }, { status: 404 });
    if (paper.created_by_id !== user.id && user.role !== 'admin') {
      return Response.json({ error: 'Forbidden' }, { status: 403 });
    }

    const now = new Date();
    const year = now.getFullYear();
    let citationId = paper.citation_id;

    // Assign a persistent Chapterly citation ID on first publish.
    if (!citationId) {
      const counterKey = `research_counter_${year}`;
      const existing = await base44.asServiceRole.entities.Setting.filter({ key: counterKey });
      let seq = 1;
      if (existing && existing.length) {
        seq = parseInt(existing[0].value, 10) + 1;
        await base44.asServiceRole.entities.Setting.update(existing[0].id, { value: String(seq) });
      } else {
        await base44.asServiceRole.entities.Setting.create({ key: counterKey, value: '1' });
      }
      citationId = `CHAP-${year}-${String(seq).padStart(4, '0')}`;
    }

    const updated = await base44.entities.ResearchPaper.update(paperId, {
      status: 'published',
      published_date: now.toISOString(),
      citation_id: citationId,
    });

    // Reconcile internal citation links from the paper's references.
    await base44.asServiceRole.entities.Citation.deleteMany({ citing_paper_id: paperId });
    const refs = (paper.references || []).filter((r) => r && r.paper_id);
    if (refs.length) {
      await base44.asServiceRole.entities.Citation.bulkCreate(
        refs.map((r) => ({ citing_paper_id: paperId, cited_paper_id: r.paper_id }))
      );
    }

    return Response.json({ paper: updated, citation_id: citationId });
  } catch (error) {
    console.error('publishResearchPaper error', error);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/publishScheduledChapters/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

export default async function(req: Request) {
  try {
    const base44 = createClientFromRequest(req);

    // Schedule-only publisher (the Publish Scheduled Chapters workflow runs as
    // its admin owner). Requiring an admin caller stops anonymous triggering.
    const user = await base44.auth.me().catch((e: any) => (e?.status === 401 ? null : Promise.reject(e)));
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
    if (user.role !== 'admin') return Response.json({ error: 'Forbidden' }, { status: 403 });

    const now = new Date().toISOString();
    // Chapters that are still hidden but whose scheduled release time has passed
    const due = await base44.asServiceRole.entities.Chapter.filter({
      published: false,
      release_date: { $lte: now }
    });
    let published = 0;
    for (const c of due) {
      if (!c.release_date) continue;
      await base44.asServiceRole.entities.Chapter.update(c.id, { published: true });
      published++;
    }
    return Response.json({ ok: true, published, checked: due.length });
  } catch (error) {
    console.error('publishScheduledChapters error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/requestPayout/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import Stripe from 'npm:stripe@17.6.0';
import { secrets } from 'base44:runtime';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to continue' }, { status: 401 });

    const stripe = new Stripe(secrets.get('STRIPE_SECRET_KEY'));
    const appId = secrets.get('BASE44_APP_ID');
    const accountId = user.stripe_account_id;
    if (!accountId) return Response.json({ error: 'Connect a Stripe account first' }, { status: 400 });

    const account = await stripe.accounts.retrieve(accountId);
    if (!account.charges_enabled) {
      return Response.json({ error: 'Complete your Stripe onboarding to receive payouts' }, { status: 400 });
    }

    const purchases = await base44.asServiceRole.entities.Purchase.filter(
      { writer_id: user.id, status: 'completed' }, '-created_date', 500
    );
    const totalEarnings = purchases.reduce((s, p) => s + (p.writer_share || 0), 0);
    const payouts = await base44.asServiceRole.entities.Payout.filter(
      { writer_id: user.id, status: 'paid' }, '-created_date', 200
    );
    const paidOut = payouts.reduce((s, p) => s + p.amount, 0);
    const available = Math.round((totalEarnings - paidOut) * 100) / 100;

    if (available <= 0) return Response.json({ error: 'No balance available to withdraw' }, { status: 400 });

    const amountCents = Math.round(available * 100);

    // Concurrency guard: the balance check above is not atomic, so parallel
    // requests can all see the same available balance. Deriving the Stripe
    // idempotency key from the writer plus the exact balance snapshot makes
    // Stripe collapse those duplicates into a single transfer (or reject the
    // in-flight duplicate) instead of paying the same earnings twice.
    const balanceEpoch = `${Math.round(totalEarnings * 100)}:${Math.round(paidOut * 100)}`;
    const idempotencyKey = `payout_${user.id}_${balanceEpoch}`;

    let transfer;
    try {
      transfer = await stripe.transfers.create({
        amount: amountCents,
        currency: 'usd',
        destination: accountId,
        metadata: { base44_app_id: appId, writer_id: user.id },
      }, { idempotencyKey });
    } catch (e: any) {
      if (e?.code === 'idempotency_key_in_use' || e?.statusCode === 409) {
        return Response.json({ error: 'A payout for this balance is already being processed. Please wait a moment.' }, { status: 409 });
      }
      throw e;
    }

    // A replayed idempotent transfer returns the same transfer id — never record
    // a second Payout row for it.
    const alreadyRecorded = await base44.asServiceRole.entities.Payout.filter({ writer_id: user.id, reference: transfer.id });
    if (alreadyRecorded && alreadyRecorded.length) {
      return Response.json({ ok: true, payout: alreadyRecorded[0], transfer_id: transfer.id, duplicate: true });
    }

    const payout = await base44.asServiceRole.entities.Payout.create({
      writer_id: user.id,
      amount: available,
      status: 'paid',
      method: 'stripe',
      reference: transfer.id,
      paid_at: new Date().toISOString(),
    });

    // Reconcile the ledger: if a concurrent request recorded the same transfer
    // first, keep only the earliest row so paid-out totals are never inflated.
    const sameTransfer = await base44.asServiceRole.entities.Payout.filter({ writer_id: user.id, reference: transfer.id });
    if (sameTransfer && sameTransfer.length > 1) {
      const keep = sameTransfer.sort((a: any, b: any) => new Date(a.created_date).getTime() - new Date(b.created_date).getTime())[0];
      if (keep.id !== payout.id) {
        await base44.asServiceRole.entities.Payout.delete(payout.id).catch(() => {});
        return Response.json({ ok: true, payout: keep, transfer_id: transfer.id, duplicate: true });
      }
    }

    return Response.json({ ok: true, payout, transfer_id: transfer.id });
  } catch (error) {
    console.error('requestPayout error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/safepayWebhook/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import { secrets } from 'base44:runtime';
import { getFeePercent, splitAmount } from '../../shared/feeSplit.ts';
import { notifyTransaction } from '../../shared/transactionNotification.ts';

// Hex → bytes for signature verification. Returns null on malformed input.
function hexToBytes(hex: string): Uint8Array | null {
  const clean = hex.trim().toLowerCase();
  if (!clean || clean.length % 2 !== 0 || !/^[0-9a-f]+$/.test(clean)) return null;
  const out = new Uint8Array(clean.length / 2);
  for (let i = 0; i < out.length; i++) out[i] = parseInt(clean.slice(i * 2, i * 2 + 2), 16);
  return out;
}

export default async function(req) {
  const sig = req.headers.get('X-SFPY-SIGNATURE') || req.headers.get('x-sfpy-signature');
  const rawBody = await req.text();
  const webhookSecret = secrets.get('SAFEPAY_WEBHOOK_SECRET');

  // Fail closed: without a configured secret we cannot verify authenticity, so
  // refuse to process anything rather than trusting unverified events.
  if (!webhookSecret) {
    console.error('safepayWebhook: SAFEPAY_WEBHOOK_SECRET not configured — refusing to process');
    return Response.json({ error: 'Webhook not configured' }, { status: 500 });
  }

  if (!sig) {
    console.error('safepayWebhook: missing signature');
    return Response.json({ error: 'Missing signature' }, { status: 400 });
  }

  // Mandatory, constant-time HMAC-SHA512 verification (SubtleCrypto.verify).
  try {
    const enc = new TextEncoder();
    const key = await crypto.subtle.importKey('raw', enc.encode(webhookSecret), { name: 'HMAC', hash: 'SHA-512' }, false, ['verify']);
    const sigBytes = hexToBytes(sig);
    if (!sigBytes) {
      console.error('safepayWebhook: malformed signature');
      return Response.json({ error: 'Invalid signature' }, { status: 400 });
    }
    const valid = await crypto.subtle.verify('HMAC', key, sigBytes, enc.encode(rawBody));
    if (!valid) {
      console.error('safepayWebhook: signature mismatch');
      return Response.json({ error: 'Invalid signature' }, { status: 400 });
    }
  } catch (e) {
    console.error('safepayWebhook: signature verify failed:', e.message);
    return Response.json({ error: 'Signature error' }, { status: 400 });
  }

  try {
    const event = JSON.parse(rawBody);
    const base44 = createClientFromRequest(req);

    if (event.type === 'payment.succeeded') {
      const data = event.data || {};
      const meta = data.metadata || {};
      const orderId = meta.order_id || '';
      const [chapter_id, reader_id, writer_id, amountStr] = orderId.split('|');
      if (chapter_id && reader_id) {
        const amount = Number(amountStr) || (Number(data.amount) / 100);
        const feePercent = await getFeePercent(base44);
        const { writerShare, platformShare } = splitAmount(amount, feePercent);
        // Idempotency: skip if we already recorded this tracker
        const existing = await base44.asServiceRole.entities.Purchase.filter({ reader_id, chapter_id, stripe_payment_id: data.tracker });
        if (!existing.length) {
          await base44.asServiceRole.entities.Purchase.create({
            reader_id,
            chapter_id,
            writer_id: writer_id || '',
            amount,
            writer_share: writerShare,
            platform_share: platformShare,
            fee_percent: feePercent,
            payment_method: 'safepay',
            status: 'completed',
            stripe_payment_id: data.tracker,
          });
          base44.analytics.track({ eventName: 'payment_completed', properties: { type: 'chapter_unlock', amount } });
          await notifyTransaction(base44, {
            userId: writer_id,
            type: 'new_chapter',
            body: `A reader unlocked a chapter for $${amount.toFixed(2)} — your share is $${writerShare.toFixed(2)}.`,
            targetId: chapter_id,
            sourceType: 'purchase',
          });
          console.log(`SafePay granted chapter ${chapter_id} to ${reader_id} (writer ${writerShare}, platform ${platformShare})`);
        }
      } else {
        console.error('safepayWebhook: missing metadata for payment.succeeded', JSON.stringify(meta));
      }
    }

    return Response.json({ received: true });
  } catch (error) {
    console.error('safepayWebhook handler error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/sendWeeklyDigest/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';

const APP_URL = 'https://read-chapterly-live.base44.app';
const WEEK_MS = 7 * 24 * 60 * 60 * 1000;

function escapeHtml(s: string): string {
  return (s || '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
}

export default async function(req: Request) {
  try {
    const base44 = createClientFromRequest(req);

    // Scheduled workflow-only mailer: require an admin caller so it cannot be
    // triggered anonymously to email-bomb every reader and burn the app quota.
    const user = await base44.auth.me().catch((e: any) => (e?.status === 401 ? null : Promise.reject(e)));
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
    if (user.role !== 'admin') return Response.json({ error: 'Forbidden' }, { status: 403 });

    const since = new Date(Date.now() - WEEK_MS).toISOString();

    // 1. Group follows by reader
    const follows = await base44.asServiceRole.entities.Follow.filter({});
    const byReader: Record<string, string[]> = {};
    for (const f of follows) {
      if (!f.follower_id || !f.writer_id) continue;
      (byReader[f.follower_id] ||= []).push(f.writer_id);
    }

    let sent = 0;
    let skipped = 0;
    for (const [readerId, writerIds] of Object.entries(byReader)) {
      let reader;
      try { reader = await base44.asServiceRole.entities.User.get(readerId); } catch { skipped++; continue; }
      if (!reader?.email) { skipped++; continue; }

      // 2. Gather chapters published in the last 7 days by followed writers
      const items: { storyTitle: string; chapterTitle: string; storyId: string; chapterId: string }[] = [];
      for (const wid of writerIds) {
        const stories = await base44.asServiceRole.entities.Story.filter({ created_by_id: wid, status: 'published' });
        for (const s of stories) {
          const chapters = await base44.asServiceRole.entities.Chapter.filter({ story_id: s.id, published: true });
          for (const c of chapters) {
            const wentLive = c.release_date || c.created_date;
            if (wentLive && new Date(wentLive) >= new Date(since)) {
              items.push({ storyTitle: s.title, chapterTitle: c.title, storyId: s.id, chapterId: c.id });
            }
          }
        }
      }

      if (items.length === 0) { skipped++; continue; }

      // 3. Compose and send the digest
      const name = reader.display_name || reader.full_name || 'there';
      const rows = items.map((it) =>
        `<tr><td style="padding:10px 0;border-bottom:1px solid #eee;">
          <a href="${APP_URL}/read/${it.chapterId}" style="color:#2563eb;text-decoration:none;font-size:16px;font-weight:600;">${escapeHtml(it.chapterTitle)}</a>
          <div style="color:#666;font-size:13px;margin-top:3px;">from <a href="${APP_URL}/story/${it.storyId}" style="color:#2563eb;text-decoration:none;">${escapeHtml(it.storyTitle)}</a></div>
        </td></tr>`
      ).join('');

      const body = `<div style="font-family:system-ui,-apple-system,sans-serif;max-width:560px;margin:0 auto;color:#222;">
        <h2 style="margin:0 0 4px;">Hi ${escapeHtml(name)},</h2>
        <p style="color:#666;margin:0 0 18px;">${items.length} new chapter${items.length > 1 ? 's' : ''} from authors you follow this week.</p>
        <table width="100%" cellpadding="0" cellspacing="0">${rows}</table>
        <p style="margin-top:24px;"><a href="${APP_URL}/discover" style="display:inline-block;background:#2563eb;color:#fff;text-decoration:none;padding:10px 20px;border-radius:999px;font-size:14px;">Discover more stories</a></p>
        <p style="color:#999;font-size:12px;margin-top:28px;">You're receiving this because you follow these authors on Chapterly.</p>
      </div>`;

      const subject = `Your weekly Chapterly digest — ${items.length} new chapter${items.length > 1 ? 's' : ''}`;
      try {
        await base44.asServiceRole.integrations.Core.SendEmail({ to: reader.email, subject, body });
        sent++;
      } catch (e) {
        console.error('digest send failed for', reader.email, e.message);
      }
    }

    return Response.json({ ok: true, sent, skipped, readers: Object.keys(byReader).length });
  } catch (error) {
    console.error('sendWeeklyDigest error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/stripeConnect/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import Stripe from 'npm:stripe@17.6.0';
import { secrets } from 'base44:runtime';

export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);
    const user = await base44.auth.me();
    if (!user) return Response.json({ error: 'Sign in to continue' }, { status: 401 });

    const body = await req.json().catch(() => ({}));
    const mode = body.mode || 'onboard';
    const origin = new URL(req.url).origin;
    const stripe = new Stripe(secrets.get('STRIPE_SECRET_KEY'));
    const appId = secrets.get('BASE44_APP_ID');

    let accountId = user.stripe_account_id;

    if (mode === 'onboard') {
      if (!accountId) {
        const account = await stripe.accounts.create({
          type: 'express',
          metadata: { base44_app_id: appId, user_id: user.id },
        });
        accountId = account.id;
        await base44.asServiceRole.entities.User.update(user.id, { stripe_account_id: accountId });
      }
      const link = await stripe.accountLinks.create({
        account: accountId,
        refresh_url: `${origin}/earnings`,
        return_url: `${origin}/earnings`,
        type: 'account_onboarding',
      });
      return Response.json({ url: link.url, account_id: accountId });
    }

    if (mode === 'dashboard') {
      if (!accountId) return Response.json({ error: 'No Stripe account connected' }, { status: 400 });
      const link = await stripe.accounts.createLoginLink(accountId);
      return Response.json({ url: link.url });
    }

    if (mode === 'status') {
      if (!accountId) return Response.json({ connected: false });
      const account = await stripe.accounts.retrieve(accountId);
      return Response.json({
        connected: true,
        charges_enabled: account.charges_enabled,
        payouts_enabled: account.payouts_enabled,
        details_submitted: account.details_submitted,
      });
    }

    return Response.json({ error: 'Invalid mode' }, { status: 400 });
  } catch (error) {
    console.error('stripeConnect error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/stripeWebhook/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.40';
import Stripe from 'npm:stripe@17.6.0';
import { secrets } from 'base44:runtime';
import { getFeePercent, splitAmount } from '../../shared/feeSplit.ts';
import { notifyTransaction } from '../../shared/transactionNotification.ts';

export default async function(req) {
  const stripe = new Stripe(secrets.get('STRIPE_SECRET_KEY'));
  const sig = req.headers.get('stripe-signature');
  const rawBody = await req.text();

  let event;
  try {
    event = await stripe.webhooks.constructEventAsync(rawBody, sig, secrets.get('STRIPE_WEBHOOK_SECRET'));
  } catch (err) {
    console.error('stripeWebhook signature verification failed:', err.message);
    return Response.json({ error: 'Invalid signature' }, { status: 400 });
  }

  try {
    const base44 = createClientFromRequest(req);

    if (event.type === 'checkout.session.completed') {
      const session = event.data.object;
      const meta = session.metadata || {};

      if (meta.type === 'chapter' && meta.chapter_id && meta.reader_id) {
        const amount = Number(meta.amount) / 100;
        const feePercent = await getFeePercent(base44);
        const { writerShare, platformShare } = splitAmount(amount, feePercent);
        await base44.asServiceRole.entities.Purchase.create({
          reader_id: meta.reader_id,
          chapter_id: meta.chapter_id,
          writer_id: meta.writer_id || '',
          amount,
          writer_share: writerShare,
          platform_share: platformShare,
          fee_percent: feePercent,
          payment_method: 'stripe',
          status: 'completed',
          stripe_payment_id: session.id,
        });
        base44.analytics.track({ eventName: 'payment_completed', properties: { type: 'chapter_unlock', amount } });
        await notifyTransaction(base44, {
          userId: meta.writer_id,
          type: 'new_chapter',
          body: `A reader unlocked a chapter for $${amount.toFixed(2)} — your share is $${writerShare.toFixed(2)}.`,
          targetId: meta.chapter_id,
          sourceType: 'purchase',
        });
        console.log(`Granted chapter ${meta.chapter_id} to ${meta.reader_id} (writer ${writerShare}, platform ${platformShare})`);
      } else if (meta.type === 'subscription' && meta.writer_id && meta.reader_id) {
        const renews = new Date(Date.now() + 30 * 86400000).toISOString();
        await base44.asServiceRole.entities.Subscription.create({
          reader_id: meta.reader_id,
          writer_id: meta.writer_id,
          status: 'active',
          price: Number(meta.price) / 100,
          renews_at: renews,
          stripe_subscription_id: session.subscription,
        });
        base44.analytics.track({ eventName: 'payment_completed', properties: { type: 'subscription', amount: Number(meta.price) / 100 } });
        await notifyTransaction(base44, {
          userId: meta.writer_id,
          type: 'follow',
          body: `A reader subscribed to you for $${(Number(meta.price) / 100).toFixed(2)}/month.`,
          targetId: meta.reader_id,
          sourceType: 'subscription',
        });
        console.log(`Granted author subscription to writer ${meta.writer_id} for ${meta.reader_id}`);
      } else if (meta.type === 'membership' && meta.reader_id) {
        const renews = new Date(Date.now() + 30 * 86400000).toISOString();
        await base44.asServiceRole.entities.Subscription.create({
          reader_id: meta.reader_id,
          writer_id: 'platform',
          type: 'membership',
          status: 'active',
          price: 9.99,
          renews_at: renews,
          stripe_subscription_id: session.subscription,
        });
        base44.analytics.track({ eventName: 'payment_completed', properties: { type: 'membership', amount: 9.99 } });
        console.log(`Granted reader membership to ${meta.reader_id}`);
      } else if (meta.type === 'tip' && meta.writer_id && meta.reader_id) {
        const amount = Number(meta.amount) / 100;
        await base44.asServiceRole.entities.Tip.create({
          reader_id: meta.reader_id,
          writer_id: meta.writer_id,
          chapter_id: meta.chapter_id || '',
          amount,
          stripe_payment_id: session.id,
        });
        base44.analytics.track({ eventName: 'payment_completed', properties: { type: 'tip', amount } });
        await notifyTransaction(base44, {
          userId: meta.writer_id,
          type: 'like',
          body: `A reader sent you a $${amount.toFixed(2)} tip. 💛`,
          targetId: meta.reader_id,
          sourceType: 'tip',
        });
        console.log(`Recorded tip of ${amount} from ${meta.reader_id} to ${meta.writer_id}`);
      } else if (meta.type === 'template' && meta.template_id && meta.reader_id && meta.creator_id) {
        const amount = Number(meta.amount) / 100;
        await base44.asServiceRole.entities.Tip.create({
          reader_id: meta.reader_id,
          writer_id: meta.creator_id,
          amount,
          stripe_payment_id: session.id,
        });
        try {
          const tmpl = await base44.asServiceRole.entities.CoverTemplate.get(meta.template_id);
          if (tmpl) await base44.asServiceRole.entities.CoverTemplate.update(meta.template_id, { usage_count: (tmpl.usage_count || 0) + 1 });
        } catch (e) {
          console.error('template usage increment failed:', e.message);
        }
        base44.analytics.track({ eventName: 'payment_completed', properties: { type: 'template', amount } });
        await notifyTransaction(base44, {
          userId: meta.creator_id,
          type: 'like',
          body: `A reader bought your cover template for $${amount.toFixed(2)}.`,
          targetId: meta.template_id,
          sourceType: 'template',
        });
        console.log(`Template ${meta.template_id} purchased by ${meta.reader_id} from ${meta.creator_id}`);
      }
    }

    if (event.type === 'invoice.paid') {
      const invoice = event.data.object;
      const subId = invoice.subscription;
      if (subId) {
        const periodEnd = invoice.lines?.data?.[0]?.period?.end;
        const renewsAt = periodEnd ? new Date(periodEnd * 1000).toISOString() : new Date(Date.now() + 30 * 86400000).toISOString();
        const subs = await base44.asServiceRole.entities.Subscription.filter({ stripe_subscription_id: subId, status: 'active' });
        for (const s of subs) {
          await base44.asServiceRole.entities.Subscription.update(s.id, { renews_at: renewsAt });
        }
      }
    }

    if (event.type === 'customer.subscription.deleted') {
      const sub = event.data.object;
      const subs = await base44.asServiceRole.entities.Subscription.filter({ stripe_subscription_id: sub.id, status: 'active' });
      for (const s of subs) {
        await base44.asServiceRole.entities.Subscription.update(s.id, { status: 'canceled' });
      }
    }

    return Response.json({ received: true });
  } catch (error) {
    console.error('stripeWebhook handler error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/functions/syncTopStoryToInstagram/entry.ts`

```typescript
import { createClientFromRequest } from 'npm:@base44/sdk@0.8.44';
import { publishStoryToInstagram } from '../../shared/instagramPublish.ts';

// Scheduled (workflow) function: picks the highest-rated published story that
// has not yet been posted to the official Chapterly Instagram feed and posts
// its cover + caption. Invoked by workflow as its admin owner; requires an admin caller.
export default async function(req) {
  try {
    const base44 = createClientFromRequest(req);

    // Scheduled workflow-only publisher: require an admin caller so nobody can
    // push arbitrary content to the app's official Instagram account or probe
    // internal rating analytics from a public endpoint.
    const user = await base44.auth.me().catch((e: any) => (e?.status === 401 ? null : Promise.reject(e)));
    if (!user) return Response.json({ error: 'Unauthorized' }, { status: 401 });
    if (user.role !== 'admin') return Response.json({ error: 'Forbidden' }, { status: 403 });

    const body = await req.json().catch(() => ({}));
    const dryRun = !!body.dry_run;

    const { accessToken } = await base44.asServiceRole.connectors.getConnection('instagram');
    if (!accessToken) return Response.json({ error: 'Instagram not connected' }, { status: 400 });

    // Gather published stories and their average ratings
    const stories = await base44.asServiceRole.entities.Story.filter({ status: 'published' });
    const ratings = await base44.asServiceRole.entities.Rating.list();
    const byStory = {};
    for (const r of ratings) {
      if (!byStory[r.story_id]) byStory[r.story_id] = { sum: 0, count: 0 };
      byStory[r.story_id].sum += r.value;
      byStory[r.story_id].count++;
    }
    const scored = stories
      .map((s) => ({
        s,
        avg: byStory[s.id] ? byStory[s.id].sum / byStory[s.id].count : 0,
        n: byStory[s.id] ? byStory[s.id].count : 0,
      }))
      .filter((x) => x.n > 0 && x.s.cover_url)
      .sort((a, b) => b.avg - a.avg || b.n - a.n);

    // Exclude stories already posted to the official feed
    const already = await base44.asServiceRole.entities.InstagramPost.filter({ scope: 'official' });
    const postedIds = new Set(already.map((p) => p.story_id));
    const pick = scored.find((x) => !postedIds.has(x.s.id));
    if (!pick) return Response.json({ skipped: true, reason: 'no new top-rated story with cover' });

    if (dryRun) {
      return Response.json({
        dry_run: true,
        story: { id: pick.s.id, title: pick.s.title, avg_rating: pick.avg, ratings: pick.n },
      });
    }

    const siteSetting = (await base44.asServiceRole.entities.Setting.filter({ key: 'public_site_url' }))[0];
    const siteUrl = siteSetting?.value || '';

    const result = await publishStoryToInstagram(base44, {
      accessToken,
      story: pick.s,
      scope: 'official',
      writerId: '',
      siteUrl,
    });
    return Response.json({ success: true, story_id: pick.s.id, ...result });
  } catch (error) {
    console.error('syncTopStoryToInstagram error:', error.message);
    return Response.json({ error: error.message }, { status: 500 });
  }
}
```

---

## `base44/mcp/config.json`

```javascript
{
  "auth": "oauth",
  "tools": {
    "entity_overrides": {
      "Story": { "operations": ["read"], "description": "Published serialized fiction: title, description, genre, tags, cover, status." },
      "Chapter": { "operations": ["read"], "description": "Chapters of a story: title, order, price, published state, views." },
      "ChapterContent": { "operations": [] },
      "Rating": { "operations": ["read"], "description": "Reader star ratings for a story, 1-5." },
      "Comment": { "operations": ["read"], "description": "Reader comments on a chapter." },
      "Follow": { "operations": ["read"], "description": "Which reader follows which writer." },
      "ReadingList": { "operations": ["read"], "description": "Stories and papers a reader saved to read later." },
      "ResearchPaper": { "operations": ["read"], "description": "Published research papers with abstract, body, authors and keywords." },
      "Citation": { "operations": ["read"], "description": "Citation links between research papers." },
      "Mention": { "operations": ["read"], "description": "Where a research paper is mentioned in stories, chapters or comments." },
      "CoverTemplate": { "operations": ["read"], "description": "Cover art templates available to writers." },
      "User": { "operations": [] },
      "Setting": { "operations": [] },
      "Notification": { "operations": [] },
      "WordCountLog": { "operations": [] },
      "ReadingProgress": { "operations": [] },
      "ReadingGoal": { "operations": [] },
      "Purchase": { "operations": [] },
      "Subscription": { "operations": [] },
      "Tip": { "operations": [] },
      "Payout": { "operations": [] },
      "ManualPayment": { "operations": [] },
      "InstagramPost": { "operations": [] },
      "Report": { "operations": [] },
      "Like": { "operations": [] }
    }
  }
}
```

---

## `base44/shared/chapterViewGuard.ts`

```typescript
// Shared request-guard helpers for chapter view & completion tracking.

const RATE_WINDOW_MS = 10 * 60 * 1000;
const rateMap = new Map<string, number>();

// Cloudflare sets cf-connecting-ip at the edge and overwrites any client-supplied
// value, so it is the connection address we can trust. x-forwarded-for and
// x-real-ip are fully caller-controlled and must never be used for security.
export function getClientIp(req: Request): string {
  return req.headers.get('cf-connecting-ip') || 'unknown';
}

// Rate-limit identity: the signed-in reader when there is one, otherwise the
// platform-set connection address. Origin/Referer are not authentication.
export function getRateLimitIdentity(userId: string | null, req: Request): string {
  return userId ? `user:${userId}` : `ip:${getClientIp(req)}`;
}

// scope ("view" | "complete") keeps view and completion limits independent
// so logging a view never blocks a completion for the same reader.
export function isRateLimited(identity: string, chapterId: string, scope: string): boolean {
  const key = `${scope}:${identity}:${chapterId}`;
  const now = Date.now();
  const last = rateMap.get(key);
  if (last && now - last < RATE_WINDOW_MS) return true;
  rateMap.set(key, now);
  if (rateMap.size > 10000) {
    for (const [k, ts] of rateMap) {
      if (now - ts > RATE_WINDOW_MS) rateMap.delete(k);
    }
  }
  return false;
}
```

---

## `base44/shared/emailSafeText.ts`

```typescript
// Shared HTML-safety helpers for outbound email.
// SendEmail renders `body` as HTML, so any user-controlled value (paper, story,
// chapter or comment titles, author names, labels) must be escaped before it is
// interpolated into the body, or the mail becomes a phishing surface.

export function escapeHtml(input: unknown): string {
  return String(input ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#39;');
}

// Email subjects are plain text: strip any markup and collapse line breaks so a
// crafted title cannot inject content into the header.
export function toPlainText(input: unknown): string {
  return String(input ?? '')
    .replace(/<[^>]*>/g, '')
    .replace(/[\r\n\t]+/g, ' ')
    .trim();
}
```

---

## `base44/shared/feeSplit.ts`

```typescript
export async function getFeePercent(base44) {
  try {
    const settings = await base44.asServiceRole.entities.Setting.filter({ key: 'platform_fee_percent' });
    if (settings.length && settings[0].value !== undefined && settings[0].value !== null) {
      const n = Number(settings[0].value);
      if (!isNaN(n)) return n;
    }
  } catch (e) {
    console.error('feeSplit getFeePercent error:', e.message);
  }
  return 20;
}

export function splitAmount(amount, feePercent) {
  const amt = Number(amount) || 0;
  const fee = Number(feePercent) || 0;
  const writerShare = Number((amt * (100 - fee) / 100).toFixed(2));
  const platformShare = Number((amt - writerShare).toFixed(2));
  return { writerShare, platformShare };
}
```

---

## `base44/shared/instagramPublish.ts`

```typescript
// Shared Instagram Content Publishing helper used by both the official
// auto-sync function and the per-writer self-publish function.
// Uses the Instagram Graph API (graph.instagram.com) with the access token
// passed as a query param (per the connector usage guide).
const IG_API = 'https://graph.instagram.com';
const IG_VERSION = 'v23.0';

function buildCaption(story, siteUrl) {
  const genre = story.genre || 'fiction';
  const tag = '#' + genre.replace(/[^a-zA-Z]/g, '');
  const parts = [
    `📖 ${story.title}`,
    story.description ? String(story.description).slice(0, 220) : '',
    `Genre: ${genre}`,
    `#Chapterly #serialfiction #indieauthors ${tag}`,
  ].filter(Boolean);
  if (siteUrl) parts.push(`Read it: ${siteUrl.replace(/\/$/, '')}/story/${story.id}`);
  return parts.join('\n\n').slice(0, 2200);
}

// Publishes a story's cover image + caption to Instagram and records an
// InstagramPost entry for dedup/history. Returns { ig_media_id, ig_username }.
export async function publishStoryToInstagram(base44, { accessToken, story, scope, writerId, siteUrl }) {
  if (!accessToken) throw new Error('Instagram access token missing');
  if (!story.cover_url) throw new Error('Story has no cover image to publish');

  // 1. Resolve the IG business account id
  const meRes = await fetch(`${IG_API}/me?fields=id,username&access_token=${accessToken}`);
  const me = await meRes.json();
  if (!me.id) throw new Error('Could not resolve Instagram account: ' + JSON.stringify(me));
  const igUserId = me.id;

  const caption = buildCaption(story, siteUrl);

  // 2. Create the media container
  const createRes = await fetch(`${IG_API}/${IG_VERSION}/${igUserId}/media?access_token=${accessToken}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ image_url: story.cover_url, caption }),
  });
  const created = await createRes.json();
  if (!created.id) throw new Error('Instagram media create failed: ' + JSON.stringify(created));
  const containerId = created.id;

  // 3. Poll processing status (images usually finish within a few seconds)
  let status = 'IN_PROGRESS';
  for (let i = 0; i < 12 && status !== 'FINISHED'; i++) {
    await new Promise((r) => setTimeout(r, 3000));
    const stRes = await fetch(`${IG_API}/${IG_VERSION}/${containerId}?fields=status_code&access_token=${accessToken}`);
    const st = await stRes.json();
    status = st.status_code || status;
    if (status === 'ERROR') throw new Error('Instagram media processing error: ' + JSON.stringify(st));
  }
  if (status !== 'FINISHED') throw new Error('Instagram media processing timed out');

  // 4. Publish the container
  const pubRes = await fetch(`${IG_API}/${IG_VERSION}/${igUserId}/media_publish?access_token=${accessToken}`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ creation_id: containerId }),
  });
  const pub = await pubRes.json();
  if (!pub.id) throw new Error('Instagram publish failed: ' + JSON.stringify(pub));

  // 5. Record the post for dedup + history
  await base44.asServiceRole.entities.InstagramPost.create({
    story_id: story.id,
    scope,
    writer_id: writerId || '',
    ig_media_id: pub.id,
    caption,
    status: 'published',
  });

  return { ig_media_id: pub.id, ig_username: me.username };
}
```

---

## `base44/shared/slackNotify.ts`

```typescript
// Posts a transaction alert to the configured Slack channel via the Slack Bot connector.
// Channel ID is read from the Setting `slack_alert_channel`.
// Silently skips when no channel is configured or the connector is unavailable,
// so transaction flows never break on a Slack failure.
export async function notifySlack(base44, text) {
  try {
    const settings = await base44.asServiceRole.entities.Setting.filter({ key: 'slack_alert_channel' });
    const channel = settings?.[0]?.value;
    if (!channel) return { skipped: true, reason: 'no channel configured' };

    const { accessToken } = await base44.asServiceRole.connectors.getConnection('slackbot');
    if (!accessToken) return { skipped: true, reason: 'no slack token' };

    const res = await fetch('https://slack.com/api/chat.postMessage', {
      method: 'POST',
      headers: { Authorization: `Bearer ${accessToken}`, 'Content-Type': 'application/json; charset=utf-8' },
      body: JSON.stringify({ channel, text, username: 'Chapterly', icon_emoji: ':books:' }),
    });
    const data = await res.json();
    if (!data.ok) console.error('notifySlack: slack rejected', data.error);
    return data;
  } catch (e) {
    console.error('notifySlack failed:', e.message);
    return { skipped: true, reason: e.message };
  }
}
```

---

## `base44/shared/transactionNotification.ts`

```typescript
import { notifySlack } from './slackNotify.ts';

// Creates an in-app Notification for the writer/creator when a transaction completes.
// Runs as service role, so it bypasses RLS to write into the recipient's notifications.
export async function notifyTransaction(base44, { userId, type, body, targetId, sourceType }) {
  if (!userId || userId === 'platform') return;
  try {
    await base44.asServiceRole.entities.Notification.create({
      user_id: userId,
      type: type || 'new_chapter',
      body,
      target_id: targetId || '',
      source_type: sourceType || 'transaction',
      read: false,
    });
  } catch (e) {
    console.error('notifyTransaction failed:', e.message);
  }
  await notifySlack(base44, body);
}
```

---

## `base44/workflows/Chapter Mention Notification.jsonc`

```javascript
{
  "name": "Chapter Mention Notification",
  "description": "When a chapter's content or publish state changes, scan its body for mentions of research papers and email their authors",
  "trigger": {
    "config": {
      "trigger_type": "entity",
      "entity_name": "Chapter",
      "events": [
        "create",
        "update"
      ]
    },
    "condition": "${ .trigger.data.published == true and (.trigger.event_type == \"create\" or (.trigger.changed_fields // []) | index(\"body\") != null or (.trigger.changed_fields // []) | index(\"title\") != null or (.trigger.changed_fields // []) | index(\"published\") != null) }"
  },
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "chapter_mention_notification",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "scan_mentions": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "notifyMentions",
            "args": {
              "source_type": "chapter",
              "source_id": "${ .trigger.entity_id }"
            }
          },
          "then": "end",
          "x-base44": {
            "title": "Scan chapter for mentions",
            "description": "Detect mentions and email authors"
          }
        }
      }
    ]
  }
}
```

---

## `base44/workflows/Citation Notification.jsonc`

```javascript
{
  "description": "When a paper cites another paper, notify the cited paper's author via dashboard and email",
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "citation_notification",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "notify_cited_author": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "notifyCitation",
            "args": {
              "citing_paper_id": "${ .trigger.data.citing_paper_id }",
              "cited_paper_id": "${ .trigger.data.cited_paper_id }"
            }
          },
          "then": "end",
          "x-base44": {
            "title": "Notify cited author",
            "description": "Dashboard + email alert"
          }
        }
      }
    ]
  },
  "name": "Citation Notification",
  "trigger": {
    "condition": null,
    "config": {
      "trigger_type": "entity",
      "events": [
        "create"
      ],
      "entity_name": "Citation"
    }
  }
}
```

---

## `base44/workflows/Comment Mention Notification.jsonc`

```javascript
{
  "name": "Comment Mention Notification",
  "description": "When a comment is posted, scan it for mentions of research papers and email their authors",
  "trigger": {
    "config": {
      "trigger_type": "entity",
      "entity_name": "Comment",
      "events": [
        "create"
      ]
    },
    "condition": null
  },
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "comment_mention_notification",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "scan_mentions": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "notifyMentions",
            "args": {
              "source_type": "comment",
              "source_id": "${ .trigger.entity_id }"
            }
          },
          "then": "end",
          "x-base44": {
            "title": "Scan comment for mentions",
            "description": "Detect mentions and email authors"
          }
        }
      }
    ]
  }
}
```

---

## `base44/workflows/Instagram Top Story Sync.jsonc`

```javascript
{
  "trigger": {
    "condition": null,
    "config": {
      "trigger_type": "scheduled",
      "events": [],
      "schedule_mode": "recurring",
      "cron_expression": "0 10 * * *",
      "one_time_date": null,
      "timezone": "UTC",
      "interval_value": null,
      "interval_unit": null,
      "interval_anchor": null,
      "ends_type": "never",
      "ends_on_date": null,
      "ends_after_count": null
    }
  },
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "instagram_top_story_sync",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "sync_top_story": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "syncTopStoryToInstagram"
          },
          "then": "end",
          "x-base44": {
            "title": "Sync top story to Instagram",
            "description": "Posts highest-rated story to official feed"
          }
        }
      }
    ]
  },
  "description": "Daily auto-post of the highest-rated community story to the official Chapterly Instagram feed",
  "name": "Instagram Top Story Sync"
}
```

---

## `base44/workflows/New Chapter Notification.jsonc`

```javascript
{
  "name": "New Chapter Notification",
  "description": "When a writer publishes a chapter, notify all followers via dashboard and email",
  "trigger": {
    "config": {
      "trigger_type": "entity",
      "entity_name": "Chapter",
      "events": [
        "update"
      ]
    },
    "condition": "${ .trigger.data.published == true and .trigger.old_data.published != true }"
  },
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "new_chapter_notification",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "notify_followers": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "notifyNewChapter",
            "args": {
              "chapter_id": "${ .trigger.entity_id }"
            }
          },
          "then": "end",
          "x-base44": {
            "title": "Notify followers",
            "description": "Dashboard + email alerts"
          }
        }
      }
    ]
  }
}
```

---

## `base44/workflows/Paper Mention Notification.jsonc`

```javascript
{
  "name": "Paper Mention Notification",
  "description": "When a published paper is created or updated, scan its text and references for mentions of other papers and email their authors",
  "trigger": {
    "config": {
      "trigger_type": "entity",
      "entity_name": "ResearchPaper",
      "events": [
        "create",
        "update"
      ]
    },
    "condition": "${ .trigger.data.status == \"published\" }"
  },
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "paper_mention_notification",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "scan_mentions": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "notifyMentions",
            "args": {
              "source_type": "paper",
              "source_id": "${ .trigger.entity_id }"
            }
          },
          "then": "end",
          "x-base44": {
            "title": "Scan paper for mentions",
            "description": "Detect mentions and email authors"
          }
        }
      }
    ]
  }
}
```

---

## `base44/workflows/Payout Email Notification.jsonc`

```javascript
{
  "name": "Payout Email Notification",
  "description": "Emails writers via Gmail when their payout is marked paid",
  "trigger": {
    "config": {
      "trigger_type": "entity",
      "entity_name": "Payout",
      "events": [
        "update"
      ]
    },
    "condition": "${ .trigger.data.status == \"paid\" and .trigger.old_data.status != \"paid\" }"
  },
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "payout_email_notification",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "send_email": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "notifyPayoutEmail",
            "args": {
              "payout_id": "${ .trigger.entity_id }"
            }
          },
          "then": "end",
          "x-base44": {
            "title": "Send payout email",
            "description": "Email the writer via Gmail"
          }
        }
      }
    ]
  }
}
```

---

## `base44/workflows/Publish Scheduled Chapters.jsonc`

```javascript
{
  "name": "Publish Scheduled Chapters",
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "publish_scheduled_chapters",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "publish_due": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "publishScheduledChapters"
          },
          "then": "end",
          "x-base44": {
            "title": "Publish due chapters"
          }
        }
      }
    ]
  },
  "description": "Publishes chapters whose scheduled release date has arrived",
  "trigger": {
    "condition": null,
    "config": {
      "trigger_type": "scheduled",
      "events": [],
      "schedule_mode": "recurring",
      "cron_expression": "*/5 * * * *",
      "one_time_date": null,
      "timezone": "Asia/Karachi",
      "interval_value": null,
      "interval_unit": null,
      "interval_anchor": null,
      "ends_type": "never",
      "ends_on_date": null,
      "ends_after_count": null
    }
  }
}
```

---

## `base44/workflows/Story Mention Notification.jsonc`

```javascript
{
  "name": "Story Mention Notification",
  "description": "When a published story is created or updated, scan its description and tags for mentions of research papers and email their authors",
  "trigger": {
    "config": {
      "trigger_type": "entity",
      "entity_name": "Story",
      "events": [
        "create",
        "update"
      ]
    },
    "condition": "${ .trigger.data.status == \"published\" }"
  },
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "story_mention_notification",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "scan_mentions": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "notifyMentions",
            "args": {
              "source_type": "story",
              "source_id": "${ .trigger.entity_id }"
            }
          },
          "then": "end",
          "x-base44": {
            "title": "Scan story for mentions",
            "description": "Detect mentions and email authors"
          }
        }
      }
    ]
  }
}
```

---

## `base44/workflows/Weekly Reader Digest.jsonc`

```javascript
{
  "description": "Sends each reader a weekly email digest of new chapters from authors they follow",
  "definition": {
    "document": {
      "dsl": "1.0.0",
      "name": "weekly_reader_digest",
      "version": "1.0",
      "namespace": "base44"
    },
    "do": [
      {
        "send_digest": {
          "call": "invoke_backend_function",
          "with": {
            "function_name": "sendWeeklyDigest"
          },
          "then": "end",
          "x-base44": {
            "title": "Send weekly digest"
          }
        }
      }
    ]
  },
  "name": "Weekly Reader Digest",
  "trigger": {
    "condition": null,
    "config": {
      "trigger_type": "scheduled",
      "events": [],
      "schedule_mode": "recurring",
      "cron_expression": "0 9 * * 1",
      "one_time_date": null,
      "timezone": "Asia/Karachi",
      "interval_value": null,
      "interval_unit": null,
      "interval_anchor": null,
      "ends_type": "never",
      "ends_on_date": null,
      "ends_after_count": null
    }
  }
}
```

---

## `src/App.jsx`

```javascript
import { Suspense, lazy } from 'react';
import { Toaster } from "@/components/ui/toaster"
import { QueryClientProvider } from '@tanstack/react-query'
import { queryClientInstance } from '@/lib/query-client'
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import PageNotFound from './lib/PageNotFound';
import { AuthProvider, useAuth } from '@/lib/AuthContext';
import UserNotRegisteredError from '@/components/UserNotRegisteredError';
import ScrollToTop from './components/ScrollToTop';
// Add page imports here
import Layout from '@/components/Layout';

// Pages are loaded on demand so first paint isn't blocked by the full app bundle
const Home = lazy(() => import('@/pages/Home'));
const Browse = lazy(() => import('@/pages/Browse'));
const Discover = lazy(() => import('@/pages/Discover'));
const StoryDetail = lazy(() => import('@/pages/StoryDetail'));
const ReadChapter = lazy(() => import('@/pages/ReadChapter'));
const WriterDashboard = lazy(() => import('@/pages/WriterDashboard'));
const StoryEditor = lazy(() => import('@/pages/StoryEditor'));
const ChapterEditor = lazy(() => import('@/pages/ChapterEditor'));
const Profile = lazy(() => import('@/pages/Profile'));
const Earnings = lazy(() => import('@/pages/Earnings'));
const Admin = lazy(() => import('@/pages/Admin'));
const MarketingDashboard = lazy(() => import('@/pages/MarketingDashboard'));
const SubscriptionAssistant = lazy(() => import('@/pages/SubscriptionAssistant'));
const TipAssistant = lazy(() => import('@/pages/TipAssistant'));
const CitationExplainer = lazy(() => import('@/pages/CitationExplainer'));
const CoverStudio = lazy(() => import('@/pages/CoverStudio'));
const ChapterEngagementReport = lazy(() => import('@/pages/ChapterEngagementReport'));
const InstagramPublish = lazy(() => import('@/pages/InstagramPublish'));
const Membership = lazy(() => import('@/pages/Membership'));
const Research = lazy(() => import('@/pages/Research'));
const ResearchPaperDetail = lazy(() => import('@/pages/ResearchPaperDetail'));
const ResearchEditor = lazy(() => import('@/pages/ResearchEditor'));
const MyCitations = lazy(() => import('@/pages/MyCitations'));
const StoryRecap = lazy(() => import('@/pages/StoryRecap'));
const ReaderCompanion = lazy(() => import('@/pages/ReaderCompanion'));
const Recommendations = lazy(() => import('@/pages/Recommendations'));
const Assistant = lazy(() => import('@/pages/Assistant'));
const Ria = lazy(() => import('@/pages/Ria'));
const Login = lazy(() => import('@/pages/Login'));
const Register = lazy(() => import('@/pages/Register'));
const ForgotPassword = lazy(() => import('@/pages/ForgotPassword'));
const ResetPassword = lazy(() => import('@/pages/ResetPassword'));
const OAuthConsent = lazy(() => import('@/pages/OAuthConsent'));
const Connect = lazy(() => import('@/pages/Connect'));
const Privacy = lazy(() => import('@/pages/Privacy'));
const Terms = lazy(() => import('@/pages/Terms'));
const Support = lazy(() => import('@/pages/Support'));
const AppSource = lazy(() => import('@/pages/AppSource'));

const AuthenticatedApp = () => {
  const { isLoadingAuth, isLoadingPublicSettings, authError, navigateToLogin } = useAuth();

  // Show loading spinner while checking app public settings or auth
  if (isLoadingPublicSettings || isLoadingAuth) {
    return (
      <div className="fixed inset-0 flex items-center justify-center">
        <div className="w-8 h-8 border-4 border-slate-200 border-t-slate-800 rounded-full animate-spin"></div>
      </div>
    );
  }

  // Handle authentication errors
  if (authError) {
    if (authError.type === 'user_not_registered') {
      return <UserNotRegisteredError />;
    } else if (authError.type === 'auth_required') {
      // Redirect to login automatically
      navigateToLogin();
      return null;
    }
  }

  // Render the main app
  return (
    <Suspense
      fallback={
        <div className="fixed inset-0 flex items-center justify-center">
          <div className="w-8 h-8 border-4 border-slate-200 border-t-slate-800 rounded-full animate-spin"></div>
        </div>
      }
    >
      <Routes>
      <Route path="/login" element={<Login />} />
      <Route path="/register" element={<Register />} />
      <Route path="/forgot-password" element={<ForgotPassword />} />
      <Route path="/reset-password" element={<ResetPassword />} />
      <Route path="/oauth/consent" element={<OAuthConsent />} />
      {/* Add your page Route elements here */}
      <Route element={<Layout />}>
        <Route path="/" element={<Home />} />
        <Route path="/discover" element={<Discover />} />
        <Route path="/browse" element={<Browse />} />
        <Route path="/library" element={<Profile />} />
        <Route path="/profile" element={<Profile />} />
        <Route path="/profile/:userId" element={<Profile />} />
        <Route path="/story/:id" element={<StoryDetail />} />
        <Route path="/read/:chapterId" element={<ReadChapter />} />
        <Route path="/dashboard" element={<WriterDashboard />} />
        <Route path="/dashboard/story/:id" element={<StoryEditor />} />
        <Route path="/dashboard/story/:storyId/chapter/:chapterId" element={<ChapterEditor />} />
        <Route path="/earnings" element={<Earnings />} />
        <Route path="/membership" element={<Membership />} />
        <Route path="/research" element={<Research />} />
        <Route path="/research/:id" element={<ResearchPaperDetail />} />
        <Route path="/dashboard/research/new" element={<ResearchEditor />} />
        <Route path="/dashboard/research/:id" element={<ResearchEditor />} />
        <Route path="/dashboard/citations" element={<MyCitations />} />
        <Route path="/recap/:storyId" element={<StoryRecap />} />
        <Route path="/companion/:storyId" element={<ReaderCompanion />} />
        <Route path="/recommendations" element={<Recommendations />} />
        <Route path="/assistant" element={<Assistant />} />
        <Route path="/ria" element={<Ria />} />
        <Route path="/connect" element={<Connect />} />
        <Route path="/privacy" element={<Privacy />} />
        <Route path="/terms" element={<Terms />} />
        <Route path="/support" element={<Support />} />
        <Route path="/source" element={<AppSource />} />
        <Route path="/admin" element={<Admin />} />
        <Route path="/marketing" element={<MarketingDashboard />} />
        <Route path="/subscription-assistant" element={<SubscriptionAssistant />} />
        <Route path="/tip-assistant" element={<TipAssistant />} />
        <Route path="/citation-explainer" element={<CitationExplainer />} />
        <Route path="/studio" element={<CoverStudio />} />
        <Route path="/dashboard/engagement" element={<ChapterEngagementReport />} />
        <Route path="/dashboard/instagram" element={<InstagramPublish />} />
      </Route>
      <Route path="*" element={<PageNotFound />} />
      </Routes>
    </Suspense>
  );
};


function App() {

  return (
    <AuthProvider>
      <QueryClientProvider client={queryClientInstance}>
        <Router>
          <ScrollToTop />
          <AuthenticatedApp />
        </Router>
        <Toaster />
      </QueryClientProvider>
    </AuthProvider>
  )
}

export default App
```

---

## `src/api/base44Client.js`

```javascript
import { createClient } from '@base44/sdk';
import { appParams } from '@/lib/app-params';

const { appId, token, functionsVersion, appBaseUrl } = appParams;

//Create a client with authentication required
export const base44 = createClient({
  appId,
  token,
  functionsVersion,
  serverUrl: '',
  requiresAuth: false,
  appBaseUrl
});

```

---

## `src/components/AIAssistantPanel.jsx`

```javascript
import { useState } from 'react';
import { base44 } from '@/api/base44Client';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Sparkles, Wand2, ArrowRight, RefreshCw, Check } from 'lucide-react';

const ACTIONS = [
  { key: 'continue', label: 'Continue', icon: ArrowRight },
  { key: 'suggest', label: 'Suggest next', icon: Sparkles },
  { key: 'rewrite', label: 'Rewrite', icon: Wand2 },
  { key: 'grammar', label: 'Grammar fix', icon: RefreshCw },
];

export default function AIAssistantPanel({ body, title, onInsert }) {
  const [selection, setSelection] = useState('');
  const [result, setResult] = useState('');
  const [loading, setLoading] = useState(false);

  const run = async (key) => {
    setLoading(true);
    setResult('');
    try {
      const res = await base44.functions.invoke('aiWritingAssistant', { action: key, content: body, selection, title });
      if (res.data?.text) setResult(res.data.text);
      else setResult(res.data?.error || 'No response.');
    } catch (e) {
      setResult(e.message);
    }
    setLoading(false);
  };

  const insert = () => {
    if (!result) return;
    const html = result.split(/\n\n+/).map((p) => `<p>${p.replace(/</g, '&lt;')}</p>`).join('');
    onInsert?.(html);
    setResult('');
  };

  return (
    <div className="rounded-xl border border-border/60 p-4 space-y-3">
      <div className="flex items-center gap-2">
        <Sparkles className="w-4 h-4 text-muted-foreground" />
        <h3 className="font-heading font-semibold text-sm">AI writing assistant</h3>
      </div>
      <p className="text-xs text-muted-foreground">Paste a passage to rewrite or check, or leave blank to work on the whole chapter. Nothing is published until you accept a suggestion.</p>
      <Textarea
        value={selection}
        onChange={(e) => setSelection(e.target.value)}
        placeholder="Optional: paste a passage to rewrite or check…"
        rows={2}
        className="text-sm"
      />
      <div className="flex flex-wrap gap-2">
        {ACTIONS.map((a) => {
          const Icon = a.icon;
          return (
            <Button key={a.key} variant="outline" size="sm" className="rounded-full" disabled={loading} onClick={() => run(a.key)}>
              <Icon className="w-3.5 h-3.5 mr-1.5" /> {a.label}
            </Button>
          );
        })}
      </div>
      {loading && <p className="text-sm text-muted-foreground">Thinking…</p>}
      {result && (
        <div className="space-y-2">
          <div className="rounded-lg bg-muted/50 p-3 text-sm whitespace-pre-wrap max-h-64 overflow-y-auto">{result}</div>
          <div className="flex gap-2">
            <Button size="sm" className="rounded-full" onClick={insert}><Check className="w-3.5 h-3.5 mr-1.5" /> Insert into chapter</Button>
            <Button size="sm" variant="ghost" className="rounded-full" onClick={() => navigator.clipboard?.writeText(result)}>Copy</Button>
          </div>
        </div>
      )}
    </div>
  );
}
```

---

## `src/components/AgentMessage.jsx`

```javascript
import { useState } from 'react';
import ReactMarkdown from 'react-markdown';
import { ChevronDown, ChevronRight, Loader2, CheckCircle2, XCircle } from 'lucide-react';

function statusInfo(status) {
  switch (status) {
    case 'success':
    case 'completed':
      return { Icon: CheckCircle2, cls: 'text-emerald-500', label: 'done', spin: false };
    case 'failed':
    case 'error':
      return { Icon: XCircle, cls: 'text-destructive', label: 'failed', spin: false };
    case 'running':
    case 'in_progress':
    case 'pending':
    default:
      return { Icon: Loader2, cls: 'text-muted-foreground', label: 'working…', spin: true };
  }
}

function ToolCall({ toolCall }) {
  const [open, setOpen] = useState(false);
  const proj = toolCall.display_projection || {};
  const hide = proj.hide_details && proj.details_redacted;
  const { Icon, cls, label, spin } = statusInfo(toolCall.status);

  let parsedResults = toolCall.results;
  if (typeof parsedResults === 'string') {
    try { parsedResults = JSON.parse(parsedResults); } catch { /* keep raw */ }
  }
  const failed =
    toolCall.status === 'failed' ||
    toolCall.status === 'error' ||
    (typeof toolCall.results === 'string' && /error|failed/i.test(toolCall.results)) ||
    (parsedResults && parsedResults.success === false);

  let args = toolCall.arguments_string;
  try { args = JSON.parse(args); } catch { /* keep raw */ }

  if (hide) {
    return (
      <div className="mt-2 text-xs flex items-center gap-1.5 text-muted-foreground">
        <Icon className={`w-3.5 h-3.5 ${spin ? 'animate-spin' : ''} ${failed ? 'text-destructive' : cls}`} />
        <span>{failed ? (proj.error_label || 'failed') : (proj.active_label || proj.label || 'working…')}</span>
      </div>
    );
  }

  return (
    <div className="mt-2 text-xs border border-border/60 rounded-lg overflow-hidden">
      <button onClick={() => setOpen(!open)} className="w-full flex items-center gap-1.5 px-2.5 py-1.5 hover:bg-muted/50">
        {open ? <ChevronDown className="w-3.5 h-3.5" /> : <ChevronRight className="w-3.5 h-3.5" />}
        <Icon className={`w-3.5 h-3.5 ${spin ? 'animate-spin' : ''} ${failed ? 'text-destructive' : cls}`} />
        <span className="font-medium">{toolCall.name}</span>
        <span className="text-muted-foreground">{failed ? 'failed' : label}</span>
      </button>
      {open && (
        <div className="px-2.5 pb-2 space-y-1.5">
          {args && (
            <div>
              <p className="text-muted-foreground mb-0.5">Parameters</p>
              <pre className="bg-muted/50 rounded p-2 overflow-x-auto text-[11px]">{typeof args === 'string' ? args : JSON.stringify(args, null, 2)}</pre>
            </div>
          )}
          {parsedResults !== undefined && (
            <div>
              <p className="text-muted-foreground mb-0.5">Result</p>
              <pre className="bg-muted/50 rounded p-2 overflow-x-auto text-[11px]">{typeof parsedResults === 'string' ? parsedResults : JSON.stringify(parsedResults, null, 2)}</pre>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

export default function AgentMessage({ message }) {
  const isUser = message.role === 'user';
  return (
    <div className={isUser ? 'flex justify-end' : 'flex justify-start'}>
      <div className={`max-w-[85%] rounded-2xl px-3.5 py-2.5 ${isUser ? 'bg-primary text-primary-foreground' : 'bg-muted/60 text-foreground'}`}>
        {message.content && (isUser
          ? <p className="text-sm whitespace-pre-wrap">{message.content}</p>
          : <div className="text-sm prose prose-sm max-w-none"><ReactMarkdown>{message.content}</ReactMarkdown></div>
        )}
        {message.tool_calls?.map((tc, i) => <ToolCall key={i} toolCall={tc} />)}
      </div>
    </div>
  );
}
```

---

## `src/components/AppFooter.jsx`

```javascript
import { Link } from 'react-router-dom';

export default function AppFooter() {
  return (
    <footer className="mt-16 pt-6 border-t border-border/60 flex flex-col sm:flex-row sm:items-center gap-3 text-xs text-muted-foreground">
      <span>© {new Date().getFullYear()} Chapterly</span>
      <nav className="sm:ml-auto flex items-center gap-4">
        <Link to="/privacy" className="hover:text-foreground transition-colors">Privacy Policy</Link>
        <Link to="/terms" className="hover:text-foreground transition-colors">Terms of Service</Link>
        <Link to="/support" className="hover:text-foreground transition-colors">Support</Link>
        <Link to="/source" className="hover:text-foreground transition-colors">App source</Link>
      </nav>
    </footer>
  );
}
```

---

## `src/components/AppleIcon.jsx`

```javascript
import React from "react";

export default function AppleIcon({ className = "w-5 h-5" }) {
  return (
    <svg className={className} viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
      <path d="M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z" />
    </svg>
  );
}
```

---

## `src/components/AuthLayout.jsx`

```javascript
import React from "react";

export default function AuthLayout({ icon: Icon, title, subtitle, footer, children }) {
  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-4">
      <div className="w-full max-w-md">
        <div className="text-center mb-10">
          <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary mb-4">
            <Icon className="w-7 h-7 text-primary-foreground" aria-hidden="true" />
          </div>
          <h1 className="text-3xl font-bold tracking-tight text-foreground">{title}</h1>
          {subtitle && <p className="text-muted-foreground mt-2">{subtitle}</p>}
        </div>
        <div className="bg-card rounded-2xl shadow-sm border border-border p-8">
          {children}
        </div>
        {footer && (
          <p className="text-center text-sm text-muted-foreground mt-6">{footer}</p>
        )}
      </div>
    </div>
  );
}

```

---

## `src/components/AuthorProfile.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { getPublicProfile } from '@/lib/publicProfiles';
import { Image } from '@/components/ui/image';
import { User as UserIcon, FileText } from 'lucide-react';

export default function AuthorProfile({ authorId, currentPaperId }) {
  const [author, setAuthor] = useState(null);
  const [works, setWorks] = useState([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let active = true;
    (async () => {
      if (!authorId) { setLoading(false); return; }
      try {
        const u = await getPublicProfile(authorId);
        if (!active) return;
        setAuthor(u);
        const all = await base44.entities.ResearchPaper.filter({ created_by_id: authorId, status: 'published' }, '-published_date', 20);
        if (!active) return;
        setWorks((all || []).filter((p) => p.id !== currentPaperId));
      } catch {
        // ignore — section simply stays hidden
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [authorId, currentPaperId]);

  if (loading) return null;
  if (!author) return null;

  const name = author.display_name || author.full_name || 'Anonymous author';
  const otherWorks = works.filter((p) => p.id !== currentPaperId);

  return (
    <section className="space-y-4 pt-6 border-t border-border/60">
      <h2 className="font-heading text-xl font-semibold flex items-center gap-2">
        <UserIcon className="w-4 h-4" /> About the author
      </h2>
      <div className="flex gap-4 items-start">
        <div className="w-14 h-14 rounded-full overflow-hidden bg-muted shrink-0 flex items-center justify-center">
          {author.avatar_url ? (
            <Image src={author.avatar_url} alt={name} className="w-full h-full" />
          ) : (
            <span className="text-lg font-medium text-muted-foreground">{name.charAt(0).toUpperCase()}</span>
          )}
        </div>
        <div className="space-y-1.5 min-w-0">
          <p className="font-medium">{name}</p>
          {author.bio ? (
            <p className="text-sm text-muted-foreground leading-relaxed whitespace-pre-wrap">{author.bio}</p>
          ) : (
            <p className="text-sm text-muted-foreground/70">No bio provided.</p>
          )}
        </div>
      </div>

      {otherWorks.length > 0 && (
        <div className="space-y-2">
          <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Other published works</p>
          <div className="grid sm:grid-cols-2 gap-2">
            {otherWorks.map((p) => (
              <Link
                key={p.id}
                to={`/research/${p.id}`}
                className="flex items-start gap-2 rounded-lg border border-border/60 p-3 hover:bg-muted/40 transition"
              >
                <FileText className="w-4 h-4 mt-0.5 text-muted-foreground shrink-0" />
                <div className="min-w-0">
                  <p className="font-medium text-sm line-clamp-2">{p.title}</p>
                  <p className="text-xs text-muted-foreground mt-0.5">{p.field || 'Research'}</p>
                </div>
              </Link>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}
```

---

## `src/components/BookmarkButton.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { Bookmark } from 'lucide-react';

export default function BookmarkButton({ targetType, targetId, className }) {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [saved, setSaved] = useState(false);

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) return;
      try {
        const existing = await base44.entities.ReadingList.filter({
          user_id: user.id,
          target_type: targetType,
          target_id: targetId,
        });
        if (active) setSaved(existing.length > 0);
      } catch {}
    })();
    return () => { active = false; };
  }, [user, targetType, targetId]);

  const toggle = async () => {
    if (!user) return toast({ title: 'Sign in to save to your reading list' });
    try {
      if (saved) {
        const existing = await base44.entities.ReadingList.filter({
          user_id: user.id,
          target_type: targetType,
          target_id: targetId,
        });
        if (existing[0]) await base44.entities.ReadingList.delete(existing[0].id);
        setSaved(false);
        toast({ title: 'Removed from reading list' });
      } else {
        await base44.entities.ReadingList.create({
          user_id: user.id,
          target_type: targetType,
          target_id: targetId,
        });
        setSaved(true);
        toast({ title: 'Saved to reading list' });
      }
    } catch (e) {
      toast({ title: 'Could not update reading list', variant: 'destructive' });
    }
  };

  return (
    <Button onClick={toggle} variant={saved ? 'default' : 'outline'} className={className || 'rounded-full'}>
      <Bookmark className={`w-4 h-4 mr-1.5 ${saved ? 'fill-current' : ''}`} />
      {saved ? 'Saved' : 'Save'}
    </Button>
  );
}
```

---

## `src/components/CitationCard.jsx`

```javascript
import { useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import html2canvas from 'html2canvas';
import { jsPDF } from 'jspdf';
import { buildCitations } from '@/lib/citations';
import { Button } from '@/components/ui/button';
import { Download, FileText, Code, Check, ExternalLink } from 'lucide-react';

export default function CitationCard({ paper }) {
  const cardRef = useRef(null);
  const [busy, setBusy] = useState(false);
  const [copied, setCopied] = useState('');
  const c = buildCitations(paper);
  const year = paper.published_date ? new Date(paper.published_date).getFullYear() : new Date().getFullYear();
  const authors = (paper.authors || []).join(', ') || 'Anonymous';

  const copy = (text, key) => {
    navigator.clipboard.writeText(text);
    setCopied(key);
    setTimeout(() => setCopied(''), 1500);
  };

  const renderCanvas = async () => {
    const canvas = await html2canvas(cardRef.current, { scale: 2, backgroundColor: '#ffffff' });
    return canvas;
  };

  const downloadPNG = async () => {
    if (!cardRef.current) return;
    setBusy(true);
    try {
      const canvas = await renderCanvas();
      const link = document.createElement('a');
      link.download = `citation-${paper.citation_id || paper.id}.png`;
      link.href = canvas.toDataURL('image/png');
      link.click();
    } catch {
      setBusy(false);
    } finally {
      setBusy(false);
    }
  };

  const downloadPDF = async () => {
    if (!cardRef.current) return;
    setBusy(true);
    try {
      const canvas = await renderCanvas();
      const img = canvas.toDataURL('image/png');
      const pdf = new jsPDF({ orientation: 'landscape', unit: 'px', format: [canvas.width, canvas.height] });
      pdf.addImage(img, 'PNG', 0, 0, canvas.width, canvas.height);
      pdf.save(`citation-${paper.citation_id || paper.id}.pdf`);
    } catch {
      setBusy(false);
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="space-y-3">
      <div
        ref={cardRef}
        style={{
          width: 640,
          maxWidth: '100%',
          background: '#ffffff',
          border: '1px solid #e5e7eb',
          borderRadius: 12,
          padding: 24,
          fontFamily: 'ui-sans-serif, system-ui, sans-serif',
        }}
      >
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
          <span style={{ fontWeight: 700, color: '#3b82f6', fontSize: 15, letterSpacing: -0.2 }}>Chapterly</span>
          {paper.citation_id && (
            <span style={{ fontSize: 11, fontFamily: 'ui-monospace, monospace', background: '#111827', color: '#ffffff', padding: '2px 8px', borderRadius: 999 }}>
              {paper.citation_id}
            </span>
          )}
        </div>
        <div style={{ fontSize: 10, letterSpacing: 1.5, color: '#9ca3af', textTransform: 'uppercase', marginBottom: 8 }}>
          Formal citation
        </div>
        <p style={{ fontSize: 15, color: '#111827', lineHeight: 1.55, margin: 0 }}>{c.apa}</p>
        <div style={{ marginTop: 16, paddingTop: 16, borderTop: '1px solid #f3f4f6' }}>
          <div style={{ fontWeight: 600, color: '#111827', fontSize: 14, marginBottom: 4 }}>{paper.title}</div>
          <div style={{ fontSize: 12, color: '#6b7280' }}>
            {authors} · {year} · {paper.field || 'Research'}
          </div>
        </div>
      </div>

      <div className="flex flex-wrap gap-2">
        <Button onClick={downloadPNG} variant="outline" size="sm" className="rounded-full" disabled={busy}>
          <Download className="w-3.5 h-3.5 mr-1.5" /> {busy ? 'Preparing…' : 'PNG'}
        </Button>
        <Button onClick={downloadPDF} variant="outline" size="sm" className="rounded-full" disabled={busy}>
          <FileText className="w-3.5 h-3.5 mr-1.5" /> PDF
        </Button>
        <Button onClick={() => copy(c.html, 'html')} variant="outline" size="sm" className="rounded-full">
          {copied === 'html' ? <Check className="w-3.5 h-3.5 mr-1.5" /> : <Code className="w-3.5 h-3.5 mr-1.5" />} HTML
        </Button>
        <Button onClick={() => copy(c.markdown, 'md')} variant="outline" size="sm" className="rounded-full">
          {copied === 'md' ? <Check className="w-3.5 h-3.5 mr-1.5" /> : <Code className="w-3.5 h-3.5 mr-1.5" />} Markdown
        </Button>
        <Link to={`/research/${paper.id}`}>
          <Button variant="ghost" size="sm" className="rounded-full">
            <ExternalLink className="w-3.5 h-3.5 mr-1.5" /> View
          </Button>
        </Link>
      </div>
    </div>
  );
}
```

---

## `src/components/CitationGenerator.jsx`

```javascript
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Check, Copy } from 'lucide-react';
import { buildCitations } from '@/lib/citations';

export default function CitationGenerator({ paper }) {
  const [tab, setTab] = useState('apa');
  const [copied, setCopied] = useState(false);

  const citations = buildCitations(paper);
  const cid = paper.citation_id || '';

  const copy = () => {
    navigator.clipboard.writeText(citations[tab]);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  const tabs = [
    { key: 'apa', label: 'APA' },
    { key: 'mla', label: 'MLA' },
    { key: 'chicago', label: 'Chicago' },
    { key: 'harvard', label: 'Harvard' },
    { key: 'bibtex', label: 'BibTeX' },
  ];

  return (
    <div className="rounded-xl border border-border/60 bg-muted/30 p-4 space-y-3">
      <div className="flex items-center justify-between gap-2 flex-wrap">
        <h3 className="font-heading text-sm font-semibold">Cite this paper</h3>
        {cid && (
          <span className="text-[11px] font-mono px-2 py-0.5 rounded-full bg-foreground text-background">{cid}</span>
        )}
      </div>
      <div className="flex flex-wrap gap-1.5">
        {tabs.map((t) => (
          <button
            key={t.key}
            onClick={() => setTab(t.key)}
            className={`px-3 py-1 rounded-full text-xs font-medium transition ${
              tab === t.key ? 'bg-foreground text-background' : 'border border-border text-muted-foreground hover:text-foreground'
            }`}
          >
            {t.label}
          </button>
        ))}
      </div>
      <pre className="text-xs text-foreground/85 whitespace-pre-wrap break-words font-mono leading-relaxed bg-card rounded-lg p-3 border border-border/60 max-h-48 overflow-auto">
        {citations[tab]}
      </pre>
      <Button onClick={copy} variant="outline" size="sm" className="rounded-full">
        {copied ? <Check className="w-3.5 h-3.5 mr-1.5" /> : <Copy className="w-3.5 h-3.5 mr-1.5" />}
        {copied ? 'Copied' : 'Copy citation'}
      </Button>
    </div>
  );
}
```

---

## `src/components/DrawerSelect.jsx`

```javascript
import { useState } from 'react';
import { ChevronDown, Check } from 'lucide-react';
import {
  Drawer,
  DrawerContent,
  DrawerHeader,
  DrawerTitle,
  DrawerDescription,
} from '@/components/ui/drawer';

/**
 * A select-style field that opens a bottom drawer sheet with the available
 * options, instead of using a native HTML <select>. Designed for mobile-first
 * forms where native selects feel out of place.
 *
 * options: [{ value, label }]
 */
export default function DrawerSelect({ label, value, options, onChange, className }) {
  const [open, setOpen] = useState(false);
  const selected = options.find((o) => o.value === value);

  return (
    <>
      <button
        type="button"
        onClick={() => setOpen(true)}
        className={`w-full h-9 rounded-md border border-input bg-background px-3 text-sm flex items-center justify-between hover:bg-muted/40 transition ${className || ''}`}
      >
        <span className="truncate">{selected?.label ?? value}</span>
        <ChevronDown className="w-4 h-4 opacity-50 shrink-0" />
      </button>
      <Drawer open={open} onOpenChange={setOpen}>
        <DrawerContent>
          <DrawerHeader className="text-left">
            <DrawerTitle>{label}</DrawerTitle>
            <DrawerDescription>Choose an option</DrawerDescription>
          </DrawerHeader>
          <div className="px-2 pb-6 max-h-[50vh] overflow-y-auto">
            {options.map((o) => (
              <button
                key={o.value}
                onClick={() => { onChange(o.value); setOpen(false); }}
                className={`w-full flex items-center justify-between px-3 py-3 rounded-lg text-sm text-left transition ${
                  o.value === value
                    ? 'bg-muted text-foreground font-medium'
                    : 'hover:bg-muted/60 text-muted-foreground'
                }`}
              >
                {o.label}
                {o.value === value && <Check className="w-4 h-4" />}
              </button>
            ))}
          </div>
        </DrawerContent>
      </Drawer>
    </>
  );
}
```

---

## `src/components/EarningsChart.jsx`

```javascript
import { useEffect, useMemo, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { BarChart, Bar, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer, CartesianGrid } from 'recharts';
import { TrendingUp } from 'lucide-react';

const MONTHS = 12;

const monthKey = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}`;
const monthLabel = (d) => d.toLocaleString('default', { month: 'short' });

export default function EarningsChart() {
  const { user } = useCurrentUser();
  const [data, setData] = useState(null);

  useEffect(() => {
    if (!user) return;
    let active = true;
    (async () => {
      try {
        const [purchases, subs, tips] = await Promise.all([
          base44.entities.Purchase.filter({ writer_id: user.id }, '-created_date', 500),
          base44.entities.Subscription.filter({ writer_id: user.id }, '-created_date', 500),
          base44.entities.Tip.filter({ writer_id: user.id }, '-created_date', 500),
        ]);
        if (!active) return;
        const now = new Date();
        const buckets = [];
        for (let i = MONTHS - 1; i >= 0; i--) {
          const d = new Date(now.getFullYear(), now.getMonth() - i, 1);
          buckets.push({ key: monthKey(d), label: monthLabel(d), chapters: 0, subscriptions: 0, tips: 0 });
        }
        const map = Object.fromEntries(buckets.map((b) => [b.key, b]));
        for (const p of purchases) {
          const k = monthKey(new Date(p.created_date));
          if (map[k]) map[k].chapters += p.writer_share || 0;
        }
        for (const s of subs) {
          if (s.status === 'canceled') continue;
          const k = monthKey(new Date(s.created_date));
          if (map[k]) map[k].subscriptions += s.price || 0;
        }
        for (const t of tips) {
          const k = monthKey(new Date(t.created_date));
          if (map[k]) map[k].tips += t.amount || 0;
        }
        buckets.forEach((b) => {
          b.chapters = +b.chapters.toFixed(2);
          b.subscriptions = +b.subscriptions.toFixed(2);
          b.tips = +b.tips.toFixed(2);
        });
        setData(buckets);
      } catch {
        if (active) setData([]);
      }
    })();
    return () => { active = false; };
  }, [user]);

  const hasData = useMemo(
    () => !!data && data.some((b) => b.chapters + b.subscriptions + b.tips > 0),
    [data]
  );

  if (!data) return <p className="text-sm text-muted-foreground">Loading earnings…</p>;

  return (
    <div className="rounded-2xl border border-border/60 p-5">
      <div className="flex items-center gap-2 mb-4">
        <TrendingUp className="w-4 h-4 text-muted-foreground" />
        <h2 className="font-heading text-xl font-semibold">Monthly earnings</h2>
      </div>
      {!hasData ? (
        <p className="text-sm text-muted-foreground py-12 text-center">
          No earnings yet. As readers unlock chapters, subscribe, or tip, your monthly breakdown will appear here.
        </p>
      ) : (
        <ResponsiveContainer width="100%" height={300}>
          <BarChart data={data} margin={{ top: 8, right: 8, bottom: 0, left: -8 }}>
            <CartesianGrid strokeDasharray="3 3" vertical={false} stroke="hsl(var(--border))" />
            <XAxis dataKey="label" tick={{ fontSize: 12 }} stroke="hsl(var(--muted-foreground))" />
            <YAxis tick={{ fontSize: 12 }} stroke="hsl(var(--muted-foreground))" tickFormatter={(v) => `$${v}`} />
            <Tooltip
              formatter={(v) => `$${Number(v).toFixed(2)}`}
              contentStyle={{ background: 'hsl(var(--popover))', border: '1px solid hsl(var(--border))', borderRadius: 8, fontSize: 12 }}
            />
            <Legend wrapperStyle={{ fontSize: 12 }} />
            <Bar dataKey="chapters" name="Chapter sales" stackId="a" fill="hsl(var(--chart-1))" />
            <Bar dataKey="subscriptions" name="Subscriptions" stackId="a" fill="hsl(var(--chart-2))" />
            <Bar dataKey="tips" name="Tips" stackId="a" fill="hsl(var(--chart-4))" radius={[4, 4, 0, 0]} />
          </BarChart>
        </ResponsiveContainer>
      )}
    </div>
  );
}
```

---

## `src/components/EditCitationDialog.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import DrawerSelect from '@/components/DrawerSelect';
import { Loader2 } from 'lucide-react';
import { base44 } from '@/api/base44Client';
import { useToast } from '@/components/ui/use-toast';

const FIELDS = [
  'Computer Science', 'Medicine', 'Biology', 'Physics', 'Chemistry',
  'Social Sciences', 'Humanities', 'Economics', 'Engineering',
  'Psychology', 'Education', 'Environmental', 'Other',
];

export default function EditCitationDialog({ paper, open, onOpenChange, onSaved }) {
  const { toast } = useToast();
  const [title, setTitle] = useState('');
  const [authors, setAuthors] = useState('');
  const [field, setField] = useState('Other');
  const [publishedDate, setPublishedDate] = useState('');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (paper && open) {
      setTitle(paper.title || '');
      setAuthors((paper.authors || []).join(', '));
      setField(paper.field || 'Other');
      setPublishedDate(paper.published_date ? paper.published_date.slice(0, 10) : '');
    }
  }, [paper, open]);

  const save = async () => {
    setSaving(true);
    try {
      const updates = {
        title: title.trim(),
        authors: authors.split(',').map((a) => a.trim()).filter(Boolean),
        field,
        published_date: publishedDate ? new Date(publishedDate).toISOString() : null,
      };
      await base44.entities.ResearchPaper.update(paper.id, updates);
      onSaved({ ...paper, ...updates });
      onOpenChange(false);
    } catch (e) {
      toast({ title: 'Could not save', description: e?.message || 'Please try again.', variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Edit citation details</DialogTitle>
        </DialogHeader>
        <div className="space-y-4 py-2">
          <div className="space-y-1.5">
            <Label htmlFor="ec-title">Title</Label>
            <Input id="ec-title" value={title} onChange={(e) => setTitle(e.target.value)} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="ec-authors">Authors (comma-separated)</Label>
            <Input id="ec-authors" value={authors} onChange={(e) => setAuthors(e.target.value)} placeholder="Jane Doe, John Smith" />
          </div>
          <div className="space-y-1.5">
            <Label>Field</Label>
            <DrawerSelect label="Field" value={field} options={FIELDS.map((f) => ({ value: f, label: f }))} onChange={setField} />
          </div>
          <div className="space-y-1.5">
            <Label htmlFor="ec-date">Published date</Label>
            <Input id="ec-date" type="date" value={publishedDate} onChange={(e) => setPublishedDate(e.target.value)} />
          </div>
          <p className="text-xs text-muted-foreground">
            These details drive the auto-generated citation. The persistent citation ID stays unchanged.
          </p>
        </div>
        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)} disabled={saving}>Cancel</Button>
          <Button onClick={save} disabled={saving || !title.trim()}>
            {saving && <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />} Save
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

---

## `src/components/GoogleIcon.jsx`

```javascript
import React from "react";

export default function GoogleIcon({ className = "w-5 h-5" }) {
  return (
    <svg className={className} viewBox="0 0 24 24" aria-hidden="true">
      <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92a5.06 5.06 0 01-2.2 3.32v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.1z" fill="hsl(var(--primary))" />
      <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="hsl(var(--secondary))" />
      <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="hsl(var(--accent))" />
      <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="hsl(var(--destructive))" />
    </svg>
  );
}

```

---

## `src/components/ImportStoryButton.jsx`

```javascript
import { useState, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Upload, Loader2 } from 'lucide-react';

const ACCEPT = '.pdf,.doc,.docx,.txt,.md,.markdown,.html,.htm,.rtf';

const countWords = (html) =>
  (html || '').replace(/<[^>]+>/g, ' ').trim().split(/\s+/).filter(Boolean).length;

export default function ImportStoryButton() {
  const navigate = useNavigate();
  const { toast } = useToast();
  const inputRef = useRef(null);
  const [busy, setBusy] = useState(false);

  const handleFile = async (e) => {
    const file = e.target.files?.[0];
    e.target.value = '';
    if (!file) return;
    setBusy(true);
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      const res = await base44.functions.invoke('importStoryFromDocument', { file_url });
      const data = res.data;
      if (!data?.title || !Array.isArray(data.chapters) || data.chapters.length === 0) {
        throw new Error('Could not read any chapters from this document.');
      }
      const story = await base44.entities.Story.create({
        title: data.title.slice(0, 200),
        description: (data.description || '').slice(0, 1000),
        cover_url: '',
        genre: 'Other',
        tags: [],
        status: 'draft',
        subscription_price: 3.99,
      });
      const chapters = data.chapters.map((c, i) => ({
        story_id: story.id,
        title: (c.title || `Chapter ${i + 1}`).slice(0, 200),
        body: c.body || '',
        status: 'free',
        price: 0,
        published: false,
        order_index: i,
        word_count: countWords(c.body),
      }));
      await base44.entities.Chapter.bulkCreate(chapters);
      toast({
        title: 'Story imported',
        description: `${chapters.length} chapter${chapters.length === 1 ? '' : 's'} added as draft.`,
      });
      navigate(`/dashboard/story/${story.id}`);
    } catch (err) {
      toast({
        title: 'Import failed',
        description: err?.message || 'Could not parse the document.',
        variant: 'destructive',
      });
    } finally {
      setBusy(false);
    }
  };

  return (
    <>
      <Button
        variant="outline"
        className="rounded-full"
        disabled={busy}
        onClick={() => inputRef.current?.click()}
      >
        {busy ? (
          <Loader2 className="w-4 h-4 mr-1.5 animate-spin" />
        ) : (
          <Upload className="w-4 h-4 mr-1.5" />
        )}
        {busy ? 'Importing…' : 'Import'}
      </Button>
      <input
        ref={inputRef}
        type="file"
        className="hidden"
        accept={ACCEPT}
        onChange={handleFile}
      />
    </>
  );
}
```

---

## `src/components/Layout.jsx`

```javascript
import { useEffect, useRef } from 'react';
import { NavLink, Outlet, useLocation, useNavigate } from 'react-router-dom';
import { BookOpen, Compass, Library, PenLine, User, Wallet, Shield, Crown, Home, GraduationCap, Bot, Sparkles, TrendingUp, Palette, Plug } from 'lucide-react';
import NotificationBell from '@/components/NotificationBell';
import SmartAppBanner from '@/components/SmartAppBanner';
import AppFooter from '@/components/AppFooter';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useIsMobile } from '@/hooks/use-mobile';
import { useSystemTheme } from '@/hooks/useSystemTheme';
import { useAndroidBackButton } from '@/hooks/useAndroidBackButton';

const bottomTabs = [
  { to: '/', label: 'Home', icon: Home, end: true },
  { to: '/discover', label: 'Discover', icon: Compass },
  { to: '/browse', label: 'Browse', icon: BookOpen },
  { to: '/research', label: 'Research', icon: GraduationCap },
  { to: '/library', label: 'Library', icon: Library },
  { to: '/dashboard', label: 'Write', icon: PenLine },
  { to: '/profile', label: 'Profile', icon: User },
];

const desktopLinks = [
  ...bottomTabs,
  { to: '/earnings', label: 'Earnings', icon: Wallet },
  { to: '/membership', label: 'Membership', icon: Crown },
  { to: '/assistant', label: 'Assistant', icon: Bot },
  { to: '/ria', label: 'Ria', icon: Sparkles },
  { to: '/studio', label: 'Covers', icon: Palette },
  { to: '/connect', label: 'Connect', icon: Plug },
];

function getTabBase(pathname) {
  if (pathname === '/') return '/';
  const tab = bottomTabs.find((t) => t.to !== '/' && (pathname === t.to || pathname.startsWith(t.to + '/')));
  return tab?.to || pathname;
}

export default function Layout() {
  const { user } = useCurrentUser();
  const isMobile = useIsMobile();
  const location = useLocation();
  const navigate = useNavigate();

  useSystemTheme();
  useAndroidBackButton();

  // Per-tab navigation history — clicking a tab returns to its last visited path
  const lastPathPerTab = useRef({});
  // Per-tab scroll positions — restored when returning to a tab
  const scrollMap = useRef({});
  const currentBase = useRef(getTabBase(location.pathname));

  useEffect(() => {
    const newBase = getTabBase(location.pathname);
    const oldBase = currentBase.current;
    if (oldBase !== newBase) {
      // Save scroll offset for the tab we are leaving
      scrollMap.current[oldBase] = window.scrollY;
      currentBase.current = newBase;
    }
    // Remember the deepest path visited within this tab
    lastPathPerTab.current[newBase] = location.pathname;
    // Restore scroll offset for the tab we are entering
    const saved = scrollMap.current[newBase] ?? 0;
    requestAnimationFrame(() => window.scrollTo(0, saved));
  }, [location.pathname]);

  // Continuously track scroll for the active tab
  useEffect(() => {
    const onScroll = () => {
      scrollMap.current[currentBase.current] = window.scrollY;
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const handleTabClick = (e, to) => {
    const target = lastPathPerTab.current[to] || to;
    if (target !== location.pathname) {
      e.preventDefault();
      navigate(target);
    }
  };

  const tabBase = getTabBase(location.pathname);

  return (
    <div className="min-h-screen bg-background text-foreground" style={{ paddingTop: 'env(safe-area-inset-top)' }}>
      <SmartAppBanner />
      {!isMobile && (
        <header className="sticky top-0 z-40 border-b border-border/60 bg-background/80 backdrop-blur-md">
          <div className="mx-auto max-w-6xl px-4 h-14 flex items-center gap-6">
            <NavLink to="/" className="font-heading text-lg font-semibold tracking-tight">
              Folio
            </NavLink>
            <div className="ml-auto flex items-center gap-3">
              <NotificationBell />
              <nav className="flex items-center gap-1">
                {desktopLinks.map((l) => {
                  const Icon = l.icon;
                  return (
                    <NavLink
                      key={l.to}
                      to={l.to}
                      end={l.end}
                      onClick={(e) => handleTabClick(e, l.to)}
                      className={({ isActive }) =>
                        `flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm transition-colors ${
                          isActive
                            ? 'bg-foreground text-background'
                            : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                        }`
                      }
                    >
                      <Icon className="w-4 h-4" />
                      <span className="hidden sm:inline">{l.label}</span>
                    </NavLink>
                  );
                })}
                {user?.role === 'admin' && (
                  <NavLink to="/marketing" className={({ isActive }) =>
                    `flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm transition-colors ${
                      isActive ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                    }`
                  }>
                    <TrendingUp className="w-4 h-4" />
                    <span className="hidden sm:inline">Marketing</span>
                  </NavLink>
                )}
                {user?.role === 'admin' && (
                  <NavLink to="/admin" className={({ isActive }) =>
                    `flex items-center gap-1.5 px-3 py-1.5 rounded-full text-sm transition-colors ${
                      isActive ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                    }`
                  }>
                    <Shield className="w-4 h-4" />
                    <span className="hidden sm:inline">Admin</span>
                  </NavLink>
                )}
              </nav>
            </div>
          </div>
        </header>
      )}
      <main
        className="mx-auto max-w-6xl px-4 py-8 sm:py-12"
        style={isMobile ? { paddingBottom: 'calc(env(safe-area-inset-bottom) + 5rem)' } : undefined}
      >
        <div key={tabBase} className="page-slide">
          <Outlet />
        </div>
        <AppFooter />
      </main>
      {isMobile && (
        <nav
          className="fixed bottom-0 left-0 right-0 z-40 border-t border-border/60 bg-background/95 backdrop-blur-md"
          style={{ paddingBottom: 'env(safe-area-inset-bottom)' }}
        >
          <div className="flex items-center justify-around h-14">
            {bottomTabs.map((l) => {
              const Icon = l.icon;
              return (
                <NavLink
                  key={l.to}
                  to={l.to}
                  end={l.end}
                  onClick={(e) => handleTabClick(e, l.to)}
                  className={({ isActive }) =>
                    `flex flex-col items-center justify-center gap-0.5 flex-1 h-full text-[10px] transition-colors ${
                      isActive ? 'text-foreground' : 'text-muted-foreground'
                    }`
                  }
                >
                  <Icon className="w-5 h-5" />
                  <span>{l.label}</span>
                </NavLink>
              );
            })}
          </div>
        </nav>
      )}
    </div>
  );
}
```

---

## `src/components/LegalLayout.jsx`

```javascript
import { Link } from 'react-router-dom';

export default function LegalLayout({ title, subtitle, updated, children }) {
  return (
    <div className="max-w-3xl mx-auto">
      <p className="text-[11px] uppercase tracking-wide text-muted-foreground">Chapterly</p>
      <h1 className="font-heading text-3xl sm:text-4xl font-semibold tracking-tight mt-2">{title}</h1>
      {subtitle && <p className="text-muted-foreground mt-3 leading-relaxed">{subtitle}</p>}
      {updated && <p className="text-xs text-muted-foreground mt-4">Last updated {updated}</p>}

      <nav className="flex flex-wrap gap-2 mt-6">
        {[
          { to: '/privacy', label: 'Privacy Policy' },
          { to: '/terms', label: 'Terms of Service' },
          { to: '/support', label: 'Support' },
        ].map((l) => (
          <Link
            key={l.to}
            to={l.to}
            className="text-xs px-3 py-1.5 rounded-full border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition-colors"
          >
            {l.label}
          </Link>
        ))}
      </nav>

      <div className="mt-8 space-y-6 text-sm leading-relaxed text-foreground/85 [&_h2]:font-heading [&_h2]:text-base [&_h2]:font-semibold [&_h2]:text-foreground [&_h2]:mt-8 [&_h2]:mb-2 [&_ul]:list-disc [&_ul]:pl-5 [&_ul]:space-y-1.5 [&_a]:underline [&_a]:underline-offset-4">
        {children}
      </div>
    </div>
  );
}
```

---

## `src/components/MfaFlow.jsx`

```javascript
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import MfaMethodSetup from "@/components/MfaMethodSetup";
import { CodeField, MfaHeader, MfaNotice, RememberDevice, ResendLine, useAppInfo, useCooldown } from "@/components/MfaParts";
import { finishSignIn, mfaSession } from "@/lib/authMfaFlow";

const SMS_RESEND_SECONDS = 60;

// The second sign-in step, for a sign-in that returned mfa_required. It is card content: a page
// shows it with `return <MfaScreen><MfaFlow ... /></MfaScreen>` in place of its own layout.
// session-record-block keeps the QR code, setup key and codes out of session recordings.
// onManage(session) is called instead of finishing when the sign-in was for managing factors.
export default function MfaFlow({ challenge, returnTo, onManage }) {
  const session = useMemo(() => mfaSession(challenge), [challenge]);
  const finish = (result) => (result.mfa_management_token && onManage ? onManage(session) : finishSignIn(result.access_token, returnTo));
  return (
    <div className="session-record-block">
      {challenge.next_step === "enroll"
        ? <Enroll session={session} onDone={finish} />
        : <Verify session={session} challenge={challenge} returnTo={returnTo} onDone={finish} />}
    </div>
  );
}

function Enroll({ session, onDone }) {
  const [method, setMethod] = useState(null);
  const info = useAppInfo();
  return (
    <>
      <MfaHeader
        title={info && `${info.name || "This app"} requires multi-factor authentication`}
        description={method ? null : "Add a second sign-in step to keep your account secure. Choose how you want to get your codes."}
      />
      {method ? (
        <MfaMethodSetup session={session} method={method} onDone={onDone} onBack={() => setMethod(null)} />
      ) : (
        <div className="space-y-3">
          <Button className="w-full h-12 font-medium" onClick={() => setMethod("totp")}>Set up your authenticator app</Button>
          <Button variant="outline" className="w-full h-12 font-medium" onClick={() => setMethod("sms")}>Enter your phone number</Button>
        </div>
      )}
    </>
  );
}

function Verify({ session, challenge, returnTo, onDone }) {
  const methods = challenge.mfa_methods;
  const [method, setMethod] = useState(methods.includes("totp") ? "totp" : "sms");
  const [code, setCode] = useState("");
  const [remember, setRemember] = useState(true);
  const [error, setError] = useState(null);
  const [busy, setBusy] = useState(false);
  const [sending, setSending] = useState(false);
  const [cooldown, setCooldown] = useCooldown();
  const sent = useRef(false);
  const phone = challenge.phone_hint || "your phone";

  const sendCode = async () => {
    setError(null);
    setSending(true);
    try {
      await session.sendSignInCode();
      setCooldown(SMS_RESEND_SECONDS);
    } catch (err) {
      setError(err);
    } finally {
      setSending(false);
    }
  };

  useEffect(() => {
    // Text the code once when SMS is the method in use; resending is the user's call.
    if (method !== "sms" || sent.current) return;
    sent.current = true;
    sendCode();
  }, [method]);

  const verify = async (value = code) => {
    if (busy || value.length < 6) return;
    setError(null);
    setBusy(true);
    try {
      onDone(await session.verify(value, method, remember));
    } catch (err) {
      setError(err);
      setCode("");
      setBusy(false);
    }
  };

  const other = methods.find((value) => value !== method);
  return (
    <>
      <MfaHeader title="Verify your identity" />
      <div className="space-y-4">
        <MfaNotice error={error} />
        <p className="text-sm text-muted-foreground text-center">
          {method === "totp" ? "Enter the code from your authenticator app"
            : sending && !cooldown ? `Sending code to ${phone}…` : `Enter the code sent to ${phone}`}
        </p>
        <CodeField id="mfa-code" value={code} onChange={setCode} onComplete={verify} />
        <RememberDevice checked={remember} onChange={setRemember} />
        <Button className="w-full h-12 font-medium" disabled={busy || code.length < 6} onClick={() => verify()}>
          {busy && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
          {busy ? "Verifying..." : "Verify"}
        </Button>
        {method === "sms" && <ResendLine cooldown={cooldown} disabled={sending} onResend={sendCode} />}
        {other && (
          <Button variant="outline" className="w-full" onClick={() => { setMethod(other); setCode(""); setError(null); }}>
            {other === "sms" ? "Verify via Text Message" : "Verify via Authenticator App"}
          </Button>
        )}
        <div className="text-center">
          <a href={returnTo && returnTo !== "/" ? "/login?returnTo=" + encodeURIComponent(returnTo) : "/login"} className="text-sm text-muted-foreground hover:underline">Back to Login</a>
        </div>
      </div>
    </>
  );
}

```

---

## `src/components/MfaManage.jsx`

```javascript
import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Loader2, Smartphone, MessageSquare } from "lucide-react";
import MfaMethodSetup from "@/components/MfaMethodSetup";
import { CodeField, MfaHeader, MfaNotice, ResendLine, useCooldown } from "@/components/MfaParts";

const METHODS = [
  { id: "totp", name: "Authenticator app", icon: Smartphone,
    description: "Use an app like Google Authenticator or Duo to generate secure sign-in codes." },
  { id: "sms", name: "Text messages", icon: MessageSquare, description: "Get sign-in codes sent to your phone by text message." },
];
const SMS_RESEND_SECONDS = 30;

// Two-factor authentication settings: enable, replace or disable a method. Card content, shown
// with <MfaScreen>. session is the mfaSession that just verified a management sign-in; its grant
// lasts a few minutes, so an expired one sends the user back through /mfa.
// The helper also offers session.forgetDevices(code, method) for a "forget remembered devices" control.
export default function MfaManage({ session, returnTo }) {
  const [status, setStatus] = useState(null);
  const [view, setView] = useState({ name: "list" });
  const [error, setError] = useState(null);

  const load = async () => {
    setError(null);
    try {
      setStatus(await session.status());
    } catch (err) {
      setError(err);
    }
  };
  useEffect(() => { load(); }, [session]);

  const back = () => { setView({ name: "list" }); load(); };

  return (
    <div className="session-record-block">
      <MfaHeader title="Two-factor authentication"
        description="Add an extra layer of protection when signing in. You'll be asked for a code each time you sign in." />
      {view.name === "setup" && <MfaMethodSetup session={session} method={view.method} signInPath="/mfa" onDone={back} onBack={() => setView({ name: "list" })} />}
      {view.name === "disable" && <Disable session={session} method={view.method} onDone={back} onBack={() => setView({ name: "list" })} />}
      {view.name === "list" && (
        <div className="space-y-4">
          <MfaNotice error={error} signInPath="/mfa" />
          {!status && !error && <Loader2 className="mx-auto w-6 h-6 animate-spin text-muted-foreground" />}
          {status && METHODS.map(({ id, name, icon: Icon, description }) => {
            const enrolled = status.methods.includes(id);
            return (
              <div key={id} className="flex flex-wrap items-center gap-3 rounded-lg border border-border p-4">
                <Icon className="w-5 h-5 text-muted-foreground shrink-0" aria-hidden="true" />
                <div className="flex-1 min-w-[10rem]">
                  <p className="font-medium">{name}</p>
                  <p className="text-sm text-muted-foreground">
                    {enrolled ? (id === "sms" && status.phone_hint ? `Enabled · ${status.phone_hint}` : "Enabled") : description}
                  </p>
                </div>
                {/* On a narrow screen the actions drop below the method instead of squeezing it. */}
                <div className="flex gap-2 ml-auto">
                  <Button size="sm" variant="outline" onClick={() => setView({ name: "setup", method: id })}>
                    {enrolled ? "Replace" : "Enable"}
                  </Button>
                  {enrolled && (
                    <Button size="sm" variant="ghost" onClick={() => setView({ name: "disable", method: id })}>
                      Disable
                    </Button>
                  )}
                </div>
              </div>
            );
          })}
          <Button className="w-full h-12 font-medium" onClick={() => { window.location.href = returnTo; }}>
            Done
          </Button>
        </div>
      )}
    </div>
  );
}

// Disables a method after a fresh code from that same method.
function Disable({ session, method, onDone, onBack }) {
  const [code, setCode] = useState("");
  const [codeSent, setCodeSent] = useState(method === "totp");
  const [error, setError] = useState(null);
  const [busy, setBusy] = useState(false);
  const [cooldown, setCooldown] = useCooldown();

  const run = async (task) => {
    setError(null);
    setBusy(true);
    try {
      return await task();
    } catch (err) {
      setError(err);
      return null;
    } finally {
      setBusy(false);
    }
  };

  const sendCode = async () => {
    if (await run(() => session.sendProofCode())) {
      setCodeSent(true);
      setCooldown(SMS_RESEND_SECONDS);
    }
  };

  const confirm = async (value = code) => {
    if (busy || value.length < 6) return;
    if (await run(() => session.removeMethod(method, value, method))) onDone();
    else setCode("");
  };

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold text-center">
        {method === "totp" ? "Enter a code from your authenticator app" : "Verify with a code sent to your phone"}
      </h2>
      <MfaNotice error={error} signInPath="/mfa" />
      {codeSent ? (
        <>
          <CodeField id="mfa-disable-code" value={code} onChange={setCode} onComplete={confirm} />
          {method === "sms" && <ResendLine cooldown={cooldown} disabled={busy} onResend={sendCode} />}
        </>
      ) : (
        <Button className="w-full h-11" disabled={busy} onClick={sendCode}>
          {busy && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
          Send Code
        </Button>
      )}
      <div className="grid grid-cols-2 gap-3 pt-2">
        <Button variant="outline" className="h-11" disabled={busy} onClick={onBack}>Cancel</Button>
        <Button className="h-11" disabled={busy || !codeSent || code.length < 6} onClick={() => confirm()}>
          {busy && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
          Verify & Disable
        </Button>
      </div>
    </div>
  );
}

```

---

## `src/components/MfaMethodSetup.jsx`

```javascript
import React, { useEffect, useRef, useState } from "react";
import { Button } from "@/components/ui/button";
import { Label } from "@/components/ui/label";
import { Loader2 } from "lucide-react";
import {
  CodeField, CopyKeyButton, INVALID_PHONE, MfaNotice, PhoneField, ResendLine,
  defaultDialCode, isPlausiblePhone, isTouchDevice, useCooldown,
} from "@/components/MfaParts";

const SMS_RESEND_SECONDS = 30;
const FULL_CODE = "Enter the full 6-digit code";

// Sets up one method: method is "totp" (authenticator app) or "sms" (text messages).
// onDone receives the server's result once the code is confirmed; onBack leaves the setup.
export default function MfaMethodSetup({ session, method, onDone, onBack, signInPath }) {
  const [setup, setSetup] = useState(null);
  const [step, setStep] = useState("start");
  const [countryCode, setCountryCode] = useState(defaultDialCode);
  const [phoneNumber, setPhoneNumber] = useState("");
  const [code, setCode] = useState("");
  const [fieldError, setFieldError] = useState(null);
  const [error, setError] = useState(null);
  const [resendError, setResendError] = useState(null);
  const [busy, setBusy] = useState(false);
  const [cooldown, setCooldown] = useCooldown();
  const started = useRef(false);
  const fullPhone = `${countryCode}${phoneNumber}`;

  // Runs a request with the buttons held; a failure goes to onError and the result is null.
  const run = async (action, onError) => {
    setBusy(true);
    try {
      return await action();
    } catch (err) {
      onError(err);
      return null;
    } finally {
      setBusy(false);
    }
  };

  useEffect(() => {
    // Each setup call issues a new secret, so start it once.
    if (method !== "totp" || started.current) return;
    started.current = true;
    run(() => session.setupAuthenticator(), setError).then((result) => result && setSetup(result));
  }, [method, session]);

  // A number that can't be real never reaches the server. A server rejection that names the phone shows
  // as the same field error; anything else shows under the field as it is.
  const sendCode = async () => {
    setFieldError(null);
    setError(null);
    setResendError(null);
    if (!isPlausiblePhone(fullPhone)) {
      setFieldError(INVALID_PHONE);
      return;
    }
    const sent = await run(() => session.sendPhoneCode(fullPhone), (err) => {
      if (err.message?.toLowerCase().includes("phone")) setFieldError(INVALID_PHONE);
      else setError(err);
    });
    if (sent) {
      setStep("code");
      setCode("");
      setCooldown(SMS_RESEND_SECONDS);
    }
  };

  const resend = async () => {
    if (cooldown > 0) return;
    setResendError(null);
    try {
      await session.sendPhoneCode(fullPhone);
      setCooldown(SMS_RESEND_SECONDS);
    } catch (err) {
      setResendError(err.message || "Failed to resend");
    }
  };

  // An incomplete code is flagged without a request. A wrong one keeps the digits and says so under them.
  const confirm = async (value = code) => {
    if (busy) return;
    if (value.length !== 6) {
      setFieldError(FULL_CODE);
      return;
    }
    setFieldError(null);
    setError(null);
    const result = await run(
      () => (method === "totp" ? session.confirmAuthenticator(value) : session.confirmPhone(value)),
      (err) => (err.mustSignInAgain ? setError(err) : setFieldError(err.message || "Invalid code")),
    );
    if (result) onDone(result);
  };

  const backToStart = () => {
    setStep("start");
    setCode("");
    setFieldError(null);
    setError(null);
    setResendError(null);
  };

  const actions = (secondary, onSecondary, primary, onPrimary, disabled = false) => (
    <div className="grid grid-cols-2 gap-3 pt-2">
      <Button variant="outline" className="h-11" disabled={busy} onClick={onSecondary}>{secondary}</Button>
      <Button className="h-11" disabled={busy || disabled} onClick={onPrimary}>
        {busy && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
        {primary}
      </Button>
    </div>
  );

  if (method === "totp" && step === "start") {
    return (
      <div className="space-y-4">
        <h2 className="text-lg font-semibold text-center">Set up your authenticator app</h2>
        <MfaNotice error={error} signInPath={signInPath} />
        {!setup && !error && <Loader2 className="mx-auto w-6 h-6 animate-spin text-muted-foreground" />}
        {setup && (isTouchDevice() ? (
          <div className="space-y-3 text-sm">
            <ol className="list-decimal pl-5 space-y-1 text-muted-foreground">
              <li>Copy the key below.</li>
              <li>In your authenticator app, add an account and paste the key.</li>
              <li>Come back here and enter the code the app shows.</li>
            </ol>
            <code className="block rounded-lg border border-border px-3 py-3 text-center font-mono font-medium tracking-wider break-all">
              {setup.secret_formatted}
            </code>
            <CopyKeyButton text={setup.secret_formatted} wide />
          </div>
        ) : (
          <div className="flex flex-col items-center gap-2 text-sm">
            <p className="font-medium">Scan the QR code with your authenticator app</p>
            <img src={setup.qr_code} alt="QR code for authenticator app setup" className="w-36 h-36 rounded-lg border border-border bg-white p-1" />
            <p className="text-muted-foreground mt-3">Can't scan the code? Enter it manually:</p>
            <div className="flex flex-wrap items-center justify-center gap-1">
              <code className="font-mono font-medium tracking-wider break-all">{setup.secret_formatted}</code>
              <CopyKeyButton text={setup.secret_formatted} />
            </div>
          </div>
        ))}
        {actions("Cancel", onBack, "Continue", () => setStep("code"), !setup)}
      </div>
    );
  }

  if (method === "sms" && step === "start") {
    const phoneError = fieldError ?? (error && !error.mustSignInAgain ? error.message : null);
    return (
      <div className="space-y-4">
        <h2 className="text-lg font-semibold text-center">Enter your phone number</h2>
        <p className="text-sm text-muted-foreground text-center">A verification code will be sent to this number to confirm it's yours.</p>
        <div className="space-y-1.5">
          <Label htmlFor="mfa-phone">Phone number</Label>
          <PhoneField
            countryCode={countryCode} onCountryCodeChange={setCountryCode}
            phoneNumber={phoneNumber} onPhoneNumberChange={(value) => { setPhoneNumber(value); setFieldError(null); }}
            error={phoneError} onSubmit={!busy && phoneNumber.length >= 4 ? sendCode : undefined}
          />
        </div>
        {error?.mustSignInAgain && <MfaNotice error={error} signInPath={signInPath} />}
        {actions("Cancel", onBack, "Send Code", sendCode, phoneNumber.length < 4)}
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <h2 className="text-lg font-semibold text-center">
        {method === "totp" ? "Enter a code from your authenticator app" : "Verify your phone number"}
      </h2>
      {method === "sms" && <p className="text-sm text-muted-foreground text-center">A 6-digit code sent to {countryCode} {phoneNumber}</p>}
      <div className="flex flex-col items-center gap-2">
        <CodeField id="mfa-setup-code" value={code} onChange={(value) => { setCode(value); setFieldError(null); }}
          onComplete={confirm} hasError={Boolean(fieldError)} />
        {fieldError && <p className="text-sm text-destructive">{fieldError}</p>}
        {method === "totp"
          ? <p className="text-xs text-muted-foreground">Codes refresh every 30 seconds.</p>
          : <ResendLine cooldown={cooldown} onResend={resend} error={resendError} />}
      </div>
      <MfaNotice error={error} signInPath={signInPath} />
      {actions("Back", backToStart, "Verify", () => confirm())}
    </div>
  );
}

```

---

## `src/components/MfaParts.jsx`

```javascript
import React, { useEffect, useRef, useState } from "react";
import { Check, ChevronsUpDown, Copy, ShieldCheck } from "lucide-react";
import { Button } from "@/components/ui/button";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Input } from "@/components/ui/input";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import { Label } from "@/components/ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { loadSignInOptions } from "@/lib/authMfaFlow";
import { safeReturnTo } from "@/lib/authReturnTo";

// Building blocks shared by MfaFlow, MfaMethodSetup and MfaManage.

let appInfo;

// The app's name and sign-in settings, as login-info reports them.
export function useAppInfo() {
  const [info, setInfo] = useState(null);
  useEffect(() => {
    appInfo ||= loadSignInOptions().catch(() => ({}));
    appInfo.then((value) => setInfo(value || {}));
  }, []);
  return info;
}

// A whole page holding one MFA card. MfaFlow and MfaManage are card content, so a page that
// shows them returns <MfaScreen> in place of its own layout instead of nesting them in its card.
export function MfaScreen({ children }) {
  return (
    <div className="min-h-screen flex items-center justify-center bg-background px-4 py-8">
      <div className="w-full max-w-md bg-card rounded-2xl shadow-sm border border-border p-8">{children}</div>
    </div>
  );
}

// An icon, a title and a description, then the step's controls. A title that waits for the app's
// name is null until it loads, so the right text appears once instead of replacing a placeholder.
export function MfaHeader({ title, description }) {
  return (
    <div className="flex flex-col items-center text-center mb-6">
      <div className="inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary mb-4">
        <ShieldCheck className="w-7 h-7 text-primary-foreground" aria-hidden="true" />
      </div>
      <h1 className="text-2xl font-bold tracking-tight text-foreground min-h-[2rem]">{title}</h1>
      {description && <p className="text-muted-foreground mt-2">{description}</p>}
    </div>
  );
}

// Six digits. Like the built-in code box, any change that leaves six digits, a paste over a full code
// included, and the Enter key both call onComplete with the code as it stands.
export function CodeField({ id, label = "Enter the 6-digit code", value, onChange, onComplete, hasError = false }) {
  return (
    <div className="space-y-2">
      <Label htmlFor={id} className="block text-center font-normal text-muted-foreground">{label}</Label>
      <InputOTP id={id} maxLength={6} value={value} autoFocus autoComplete="one-time-code" containerClassName="justify-center"
        onChange={(next) => { onChange(next); if (next.length === 6) onComplete?.(next); }}
        onKeyDown={(e) => { if (e.key === "Enter" && onComplete) { e.preventDefault(); onComplete(value); } }}>
        <InputOTPGroup>
          {[0, 1, 2, 3, 4, 5].map((index) => (
            <InputOTPSlot key={index} index={index} className={hasError ? "border-destructive" : undefined} />
          ))}
        </InputOTPGroup>
      </InputOTP>
    </div>
  );
}

// "Didn't receive a code? Resend", counting down while a resend isn't allowed yet.
export function ResendLine({ cooldown, disabled, onResend, error }) {
  return (
    <div className="space-y-1 text-center">
      <p className="text-sm text-muted-foreground">
        Didn't receive a code?{" "}
        {cooldown > 0 ? (
          <span>Resend in {cooldown}s</span>
        ) : (
          <button type="button" disabled={disabled} onClick={onResend} className="font-semibold text-foreground hover:underline disabled:opacity-50">
            Resend
          </button>
        )}
      </p>
      {error && <p className="text-sm text-destructive">{error}</p>}
    </div>
  );
}

// ---- Phone number entry: the built-in screen's country picker and checks, without a phone-number library.

export const INVALID_PHONE = "Invalid phone number. Please check the number and try again.";

// Dial code of every country (iso2 + digits), from country-telephone-data, which the built-in picker lists.
const COUNTRY_DIAL_CODES = new Map(
  "af93 ax358 al355 dz213 as1684 ad376 ao244 ai1264 aq672 ag1268 ar54 am374 aw297 au61 at43 az994 bs1242 bh973 bd880 bb1246 by375 be32 bz501 bj229 bm1441 bt975 bo591 ba387 bw267 bv47 br55 io246 vg1284 bn673 bg359 bf226 bi257 kh855 cm237 ca1 cv238 bq599 ky1345 cf236 td235 cl56 cn86 cx61 cc61 co57 km269 cd243 cg242 ck682 cr506 ci225 hr385 cu53 cw599 cy357 cz420 dk45 dj253 dm1767 do1 ec593 eg20 sv503 gq240 er291 ee372 et251 fk500 fo298 fj679 fi358 fr33 gf594 pf689 tf262 ga241 gm220 ge995 de49 gh233 gi350 gr30 gl299 gd1473 gp590 gu1671 gt502 gg44 gn224 gw245 gy592 ht509 hm672 hn504 hk852 hu36 is354 in91 id62 ir98 iq964 ie353 im44 il972 it39 jm1876 jp81 je44 jo962 kz7 ke254 ki686 xk383 kw965 kg996 la856 lv371 lb961 ls266 lr231 ly218 li423 lt370 lu352 mo853 mk389 mg261 mw265 my60 mv960 ml223 mt356 mh692 mq596 mr222 mu230 yt262 mx52 fm691 md373 mc377 mn976 me382 ms1664 ma212 mz258 mm95 na264 nr674 np977 nl31 nc687 nz64 ni505 ne227 ng234 nu683 nf672 kp850 mp1670 no47 om968 pk92 pw680 ps970 pa507 pg675 py595 pe51 ph63 pn64 pl48 pt351 pr1 qa974 re262 ro40 ru7 rw250 bl590 sh290 kn1869 lc1758 mf590 pm508 vc1784 ws685 sm378 st239 sa966 sn221 rs381 sc248 sl232 sg65 sx1721 sk421 si386 sb677 so252 za27 gs500 kr82 ss211 es34 lk94 sd249 sr597 sj47 sz268 se46 ch41 sy963 tw886 tj992 tz255 th66 tl670 tg228 tk690 to676 tt1868 tn216 tr90 tm993 tc1649 tv688 vi1340 ug256 ua380 ae971 gb44 us1 um1 uy598 uz998 vu678 va39 ve58 vn84 wf681 eh212 ye967 zm260 zw263".split(" ").map((entry) => [entry.slice(0, 2), entry.slice(2)]),
);
const DIAL_CODES = [...new Set(COUNTRY_DIAL_CODES.values())].sort((a, b) => Number(a) - Number(b));

// The dial code of the browser's region (en-DE → +49), else +1.
export function defaultDialCode() {
  const region = typeof navigator === "undefined" ? undefined : navigator.language.split("-")[1]?.toLowerCase();
  const dialCode = region && COUNTRY_DIAL_CODES.get(region);
  return dialCode ? `+${dialCode}` : "+1";
}

// The built-in screen asks libphonenumber whether the number is valid for its country. Here only the
// length E.164 allows is checked (the shortest real numbers have 7 digits in all, the longest 15); the
// server runs the full per-country check before any text is sent, and answers with the same message.
export function isPlausiblePhone(fullPhone) {
  const digits = fullPhone.replace(/\D/g, "");
  return digits.length >= 7 && digits.length <= 15;
}

const matchesSearch = (code, search) => {
  const normalized = search.replace(/\+/g, "");
  return normalized === "" || code.startsWith(normalized);
};

// A searchable list of dial codes. Typing narrows it, and closing it with one match left picks that one.
function DialCodePicker({ value, onChange }) {
  const [open, setOpen] = useState(false);
  const search = useRef("");

  const handleOpenChange = (next) => {
    if (!next && search.current) {
      const matches = DIAL_CODES.filter((code) => matchesSearch(code, search.current));
      if (matches.length === 1) onChange(`+${matches[0]}`);
      search.current = "";
    }
    setOpen(next);
  };

  return (
    <Popover open={open} onOpenChange={handleOpenChange} modal>
      <PopoverTrigger asChild>
        <Button type="button" variant="outline" role="combobox" aria-expanded={open} aria-label="Country code"
          className="h-10 w-[100px] justify-between px-2.5 font-normal shadow-none">
          {value}
          <ChevronsUpDown className="ml-1 h-3.5 w-3.5 shrink-0 opacity-50" aria-hidden="true" />
        </Button>
      </PopoverTrigger>
      <PopoverContent className="w-[140px] p-0" align="start" side="bottom" avoidCollisions={false}>
        <Command filter={(item, text) => (matchesSearch(item, text) ? 1 : 0)}>
          <CommandInput placeholder="Search..." className="h-9" onValueChange={(text) => { search.current = text; }} />
          <CommandList>
            <CommandEmpty>No match</CommandEmpty>
            <CommandGroup>
              {DIAL_CODES.map((code) => (
                <CommandItem key={code} value={code} onSelect={() => { onChange(`+${code}`); search.current = ""; setOpen(false); }}>
                  +{code}
                  <Check className={cn("ml-auto h-3.5 w-3.5", value === `+${code}` ? "opacity-100" : "opacity-0")} aria-hidden="true" />
                </CommandItem>
              ))}
            </CommandGroup>
          </CommandList>
        </Command>
      </PopoverContent>
    </Popover>
  );
}

// Dial code picker plus the number (digits only, 15 at most). Once 4 digits are in, a number that can't
// be real is flagged as you type; `error` (from a failed send) takes the place of that message.
export function PhoneField({ countryCode, onCountryCodeChange, phoneNumber, onPhoneNumberChange, error, onSubmit }) {
  const [touched, setTouched] = useState(false);
  const invalid = touched && phoneNumber.length >= 4 && !isPlausiblePhone(`${countryCode}${phoneNumber}`);
  const message = error ?? (invalid ? INVALID_PHONE : null);
  return (
    <div className="space-y-1.5">
      <div className="flex gap-2">
        <DialCodePicker value={countryCode} onChange={onCountryCodeChange} />
        <Input id="mfa-phone" type="tel" autoComplete="tel-national" autoFocus value={phoneNumber} maxLength={15}
          placeholder="5551234567" aria-invalid={Boolean(message)}
          onChange={(e) => { onPhoneNumberChange(e.target.value.replace(/\D/g, "")); setTouched(true); }}
          onKeyDown={(e) => { if (e.key === "Enter" && onSubmit) { e.preventDefault(); onSubmit(); } }}
          className={cn("h-10 flex-1", message && "border-destructive focus-visible:ring-destructive")} />
      </div>
      {message
        ? <p className="text-sm text-destructive">{message}</p>
        : <p className="text-sm text-muted-foreground">Standard message and data rates may apply.</p>}
    </div>
  );
}

// Copies the setup key: an icon next to the key, or with `wide` the full-width "Copy key" button used on phones.
export function CopyKeyButton({ text, wide = false }) {
  const [copied, setCopied] = useState(false);
  const copy = async () => {
    await navigator.clipboard.writeText(text.replace(/\s/g, ""));
    setCopied(true);
    setTimeout(() => setCopied(false), 2000);
  };
  if (wide) {
    return (
      <Button type="button" variant="outline" className="w-full h-11" onClick={copy}>
        {copied ? "Copied" : "Copy key"}
      </Button>
    );
  }
  return (
    <button type="button" onClick={copy} title="Copy to clipboard" aria-label="Copy to clipboard"
      className="inline-flex items-center justify-center rounded-md p-2 text-muted-foreground hover:text-foreground hover:bg-muted">
      {copied ? <Check className="w-4 h-4" aria-hidden="true" /> : <Copy className="w-4 h-4" aria-hidden="true" />}
    </button>
  );
}

// An expired or used-up challenge can't be retried: send the user back through sign-in
// (signInPath "/mfa" for factor management, whose sign-in lives on that page). The server's
// wording for that case already says "sign in again", so it is replaced, not repeated.
export function MfaNotice({ error, signInPath = "/login" }) {
  if (!error) return null;
  const returnTo = safeReturnTo();
  return (
    <div role="alert" className="mb-4 p-3 rounded-lg bg-destructive/10 text-destructive text-sm text-center">
      {error.mustSignInAgain ? (
        <>
          Your sign-in expired.{" "}
          <a href={signInPath + (returnTo !== "/" ? "?returnTo=" + encodeURIComponent(returnTo) : "")} className="font-medium underline">
            Sign in again
          </a>
        </>
      ) : (error.message || "Verification failed. Please try again.")}
    </div>
  );
}

export function RememberDevice({ checked, onChange }) {
  return (
    <label className="flex items-center justify-center gap-2 text-sm text-muted-foreground">
      <input type="checkbox" className="h-4 w-4 accent-primary" checked={checked} onChange={(e) => onChange(e.target.checked)} />
      Remember this device for 30 days
    </label>
  );
}

// Seconds left before another text message can be sent.
export function useCooldown() {
  const [left, setLeft] = useState(0);
  useEffect(() => {
    if (left <= 0) return undefined;
    const timer = setTimeout(() => setLeft(left - 1), 1000);
    return () => clearTimeout(timer);
  }, [left]);
  return [left, setLeft];
}

// Phones and tablets run the authenticator app on this device, so a QR code can't be scanned.
export function isTouchDevice() {
  return typeof window !== "undefined" && window.matchMedia?.("(pointer: coarse)").matches;
}

```

---

## `src/components/NotificationBell.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Bell } from 'lucide-react';

function notifRoute(n) {
  if (!n.target_id) return '/';
  if (n.type === 'citation') return `/research/${n.target_id}`;
  if (n.type === 'mention') {
    if (n.source_type === 'paper') return `/research/${n.target_id}`;
    if (n.source_type === 'story') return `/story/${n.target_id}`;
    return `/read/${n.target_id}`;
  }
  return `/read/${n.target_id}`;
}

export default function NotificationBell() {
  const { user } = useCurrentUser();
  const [items, setItems] = useState([]);
  const [open, setOpen] = useState(false);
  const ref = useRef(null);

  const fetchItems = () => {
    if (!user) return;
    base44.entities.Notification.filter({ user_id: user.id }, '-created_date', 20)
      .then(setItems)
      .catch(() => {});
  };

  useEffect(() => {
    fetchItems();
    const unsub = base44.entities.Notification.subscribe(() => fetchItems());
    return () => unsub();
  }, [user]);

  useEffect(() => {
    const onClick = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener('mousedown', onClick);
    return () => document.removeEventListener('mousedown', onClick);
  }, []);

  const unread = items.filter((n) => !n.read).length;

  const markRead = async () => {
    if (!unread) return;
    const unreadItems = items.filter((n) => !n.read);
    await base44.entities.Notification.bulkUpdate(unreadItems.map((n) => ({ id: n.id, read: true })));
    setItems((prev) => prev.map((n) => ({ ...n, read: true })));
  };

  if (!user) return null;

  return (
    <div className="relative" ref={ref}>
      <button
        onClick={() => { const willOpen = !open; setOpen(willOpen); if (willOpen) markRead(); }}
        className="relative p-1.5 rounded-full hover:bg-muted text-muted-foreground hover:text-foreground"
      >
        <Bell className="w-4 h-4" />
        {unread > 0 && (
          <span className="absolute -top-0.5 -right-0.5 min-w-4 h-4 px-1 rounded-full bg-foreground text-background text-[10px] flex items-center justify-center">{unread}</span>
        )}
      </button>
      {open && (
        <div className="absolute right-0 mt-2 w-72 rounded-xl border border-border bg-popover shadow-lg z-50 overflow-hidden">
          {items.length === 0 ? (
            <p className="p-4 text-sm text-muted-foreground text-center">No notifications yet.</p>
          ) : (
            <div className="max-h-80 overflow-y-auto divide-y divide-border">
              {items.map((n) => (
                <Link
                  key={n.id}
                  to={notifRoute(n)}
                  onClick={() => setOpen(false)}
                  className="block px-4 py-3 hover:bg-muted/50 transition"
                >
                  <p className="text-sm">{n.body}</p>
                  {!n.read && <span className="inline-block w-1.5 h-1.5 rounded-full bg-foreground mt-1.5" />}
                </Link>
              ))}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
```

---

## `src/components/Paywall.jsx`

```javascript
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Lock, Sparkles, Building2, Clock, CreditCard } from 'lucide-react';
import AppleIcon from '@/components/AppleIcon';

function useApplePayAvailable() {
  const [available, setAvailable] = useState(false);
  useEffect(() => {
    if (typeof window === 'undefined' || !window.ApplePaySession) return;
    try {
      setAvailable(window.ApplePaySession.canMakePayments());
    } catch (e) {
      // no-op
    }
  }, []);
  return available;
}

export default function Paywall({ chapter, onUnlock, onSubscribe, subscriptionPrice, onBankPay, onSafepay, pendingManual, bankDetails }) {
  const [showBank, setShowBank] = useState(false);
  const [reference, setReference] = useState('');
  const applePayAvailable = useApplePayAvailable();

  const submitBank = () => {
    if (!reference.trim()) return;
    onBankPay?.(reference.trim());
    setReference('');
    setShowBank(false);
  };

  if (pendingManual) {
    return (
      <div className="rounded-2xl border border-border bg-muted/40 p-8 text-center">
        <div className="mx-auto w-12 h-12 rounded-full bg-foreground text-background flex items-center justify-center mb-4">
          <Clock className="w-5 h-5" />
        </div>
        <h3 className="font-heading text-xl font-semibold">Payment verification in progress</h3>
        <p className="text-sm text-muted-foreground mt-1.5 max-w-md mx-auto">
          Your bank transfer for “{chapter.title}” is being verified. You'll gain access as soon as it's confirmed — usually within a day.
        </p>
      </div>
    );
  }

  return (
    <div className="rounded-2xl border border-border bg-muted/40 p-8 text-center">
      <div className="mx-auto w-12 h-12 rounded-full bg-foreground text-background flex items-center justify-center mb-4">
        <Lock className="w-5 h-5" />
      </div>
      <h3 className="font-heading text-xl font-semibold">This is a premium chapter</h3>
      <p className="text-sm text-muted-foreground mt-1.5 max-w-md mx-auto">
        Unlock “{chapter.title}” to keep reading, or subscribe to the author for unlimited access to every paywalled chapter.
      </p>
      <div className="mt-6 flex flex-col sm:flex-row gap-2 justify-center">
        {applePayAvailable && (
          <Button onClick={onUnlock} className="rounded-full bg-black text-white border-black hover:bg-black/90">
            <AppleIcon className="w-4 h-4 mr-1.5" />
            Apple Pay
          </Button>
        )}
        <Button onClick={onUnlock} className="rounded-full">
          <CreditCard className="w-4 h-4 mr-1.5" />
          Unlock for ${Number(chapter.price || 0).toFixed(2)}
        </Button>
        {subscriptionPrice != null && (
          <Button onClick={onSubscribe} variant="outline" className="rounded-full">
            <Sparkles className="w-4 h-4 mr-1.5" />
            Subscribe for ${Number(subscriptionPrice).toFixed(2)}/mo
          </Button>
        )}
        {onSafepay && (
          <Button onClick={onSafepay} className="rounded-full">
            <CreditCard className="w-4 h-4 mr-1.5" />
            Pay with SafePay
          </Button>
        )}
        <Button onClick={() => setShowBank((v) => !v)} variant="ghost" className="rounded-full">
          <Building2 className="w-4 h-4 mr-1.5" />
          Pay by bank transfer
        </Button>
      </div>
      {showBank && (
        <div className="mt-5 text-left rounded-xl border border-border bg-background p-4 space-y-3">
          {bankDetails ? (
            <p className="text-xs text-muted-foreground whitespace-pre-wrap">{bankDetails}</p>
          ) : (
            <p className="text-xs text-muted-foreground">Bank details will appear here once the platform configures them. Contact support for transfer instructions.</p>
          )}
          <Textarea
            value={reference}
            onChange={(e) => setReference(e.target.value)}
            placeholder="Enter your payment reference / transaction ID"
            rows={2}
            className="text-sm"
          />
          <Button onClick={submitBank} size="sm" className="rounded-full w-full" disabled={!reference.trim()}>
            I've sent the transfer — submit for verification
          </Button>
        </div>
      )}
      <p className="text-[11px] text-muted-foreground mt-4">
        Payments are secured by SafePay. Bank transfer is verified manually before access is granted.
      </p>
    </div>
  );
}
```

---

## `src/components/ProtectedRoute.jsx`

```javascript
import { useEffect } from 'react';
import { Outlet } from 'react-router-dom';
import { useAuth } from '@/lib/AuthContext';
import UserNotRegisteredError from '@/components/UserNotRegisteredError';

const DefaultFallback = () => (
  <div className="fixed inset-0 flex items-center justify-center">
    <div className="w-8 h-8 border-4 border-slate-200 border-t-slate-800 rounded-full animate-spin"></div>
  </div>
);

export default function ProtectedRoute({ fallback = <DefaultFallback />, unauthenticatedElement }) {
  const { isAuthenticated, isLoadingAuth, authChecked, authError, checkUserAuth } = useAuth();

  useEffect(() => {
    if (!authChecked && !isLoadingAuth) {
      checkUserAuth();
    }
  }, [authChecked, isLoadingAuth, checkUserAuth]);

  if (isLoadingAuth || !authChecked) {
    return fallback;
  }

  if (authError) {
    if (authError.type === 'user_not_registered') {
      return <UserNotRegisteredError />;
    }
    return unauthenticatedElement;
  }

  if (!isAuthenticated) {
    return unauthenticatedElement;
  }

  return <Outlet />;
}

```

---

## `src/components/PullToRefresh.jsx`

```javascript
import { useRef, useState, useEffect } from 'react';
import { Loader2, RefreshCw } from 'lucide-react';

const THRESHOLD = 70;

/**
 * Wraps a scrollable page area and provides native-style pull-to-refresh.
 * Detects a downward drag when the window is scrolled to the top, shows a
 * spinner, and calls `onRefresh` (which should return a Promise) when the
 * pull exceeds the threshold.
 */
export default function PullToRefresh({ onRefresh, children }) {
  const [pull, setPull] = useState(0);
  const [refreshing, setRefreshing] = useState(false);
  const startY = useRef(0);
  const pulling = useRef(false);
  const currentPull = useRef(0);
  const refreshingRef = useRef(false);

  useEffect(() => { refreshingRef.current = refreshing; }, [refreshing]);

  useEffect(() => {
    const onTouchStart = (e) => {
      if (window.scrollY > 0 || refreshingRef.current) return;
      startY.current = e.touches[0].clientY;
      pulling.current = true;
    };
    const onTouchMove = (e) => {
      if (!pulling.current || refreshingRef.current) return;
      const delta = e.touches[0].clientY - startY.current;
      if (delta > 0 && window.scrollY <= 0) {
        const p = Math.min(delta * 0.5, THRESHOLD * 1.5);
        currentPull.current = p;
        setPull(p);
      }
    };
    const onTouchEnd = async () => {
      if (!pulling.current) return;
      pulling.current = false;
      if (currentPull.current >= THRESHOLD) {
        setRefreshing(true);
        setPull(THRESHOLD);
        try {
          await onRefresh?.();
        } finally {
          setRefreshing(false);
          setPull(0);
          currentPull.current = 0;
        }
      } else {
        setPull(0);
        currentPull.current = 0;
      }
    };

    window.addEventListener('touchstart', onTouchStart, { passive: true });
    window.addEventListener('touchmove', onTouchMove, { passive: true });
    window.addEventListener('touchend', onTouchEnd, { passive: true });
    return () => {
      window.removeEventListener('touchstart', onTouchStart);
      window.removeEventListener('touchmove', onTouchMove);
      window.removeEventListener('touchend', onTouchEnd);
    };
  }, [onRefresh]);

  return (
    <>
      <div
        className="flex items-center justify-center overflow-hidden transition-all duration-200 ease-out"
        style={{ height: refreshing ? THRESHOLD : pull }}
      >
        {refreshing ? (
          <Loader2 className="w-5 h-5 animate-spin text-muted-foreground" />
        ) : pull > 0 ? (
          <RefreshCw
            className="w-5 h-5 text-muted-foreground transition-transform"
            style={{ transform: `rotate(${pull * 3}deg)` }}
          />
        ) : null}
      </div>
      {children}
    </>
  );
}
```

---

## `src/components/PurchaseHistory.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { getPublicProfile } from '@/lib/publicProfiles';

export default function PurchaseHistory() {
  const { user } = useCurrentUser();
  const [items, setItems] = useState(null);

  useEffect(() => {
    if (!user) return;
    let active = true;
    (async () => {
      try {
        const purchases = await base44.entities.Purchase.filter(
          { reader_id: user.id, status: 'completed' },
          '-created_date',
          200
        );
        const storyCache = {};
        const writerCache = {};
        const enriched = [];
        for (const p of purchases) {
          let chapter = null;
          try { chapter = await base44.entities.Chapter.get(p.chapter_id); } catch {}
          let storyTitle = '';
          let writerName = '';
          if (chapter) {
            if (!storyCache[chapter.story_id]) {
              try { storyCache[chapter.story_id] = await base44.entities.Story.get(chapter.story_id); } catch {}
            }
            const story = storyCache[chapter.story_id];
            storyTitle = story?.title || '';
            const wid = p.writer_id || story?.created_by_id;
            if (wid && !writerCache[wid]) {
              try { writerCache[wid] = await getPublicProfile(wid); } catch {}
            }
            writerName = writerCache[wid]?.display_name || writerCache[wid]?.full_name || '';
          }
          enriched.push({ ...p, chapter, storyTitle, writerName });
        }
        if (active) setItems(enriched);
      } catch {
        if (active) setItems([]);
      }
    })();
    return () => { active = false; };
  }, [user]);

  if (!items) return <p className="text-sm text-muted-foreground">Loading purchase history…</p>;

  const methodLabel = (m) => (m === 'manual' ? 'Bank transfer' : m === 'safepay' ? 'SafePay' : 'Card');

  return (
    <section>
      <h2 className="font-heading text-xl font-semibold mb-4">Purchase history ({items.length})</h2>
      {items.length === 0 ? (
        <p className="text-sm text-muted-foreground">Chapters you pay to unlock will appear here with their payment details.</p>
      ) : (
        <div className="divide-y divide-border rounded-xl border border-border/60 overflow-hidden">
          {items.map((p) => (
            <div key={p.id} className="flex items-center justify-between gap-3 px-4 py-3">
              <div className="min-w-0">
                <p className="font-medium text-sm truncate">{p.chapter?.title || 'Chapter unavailable'}</p>
                <p className="text-xs text-muted-foreground truncate">
                  {p.storyTitle && <>{p.storyTitle} · </>}
                  {p.writerName && <>by {p.writerName} · </>}
                  {methodLabel(p.payment_method)} · {new Date(p.created_date).toLocaleDateString()}
                </p>
              </div>
              <div className="flex items-center gap-3 shrink-0">
                <span className="text-sm font-semibold">${Number(p.amount || 0).toFixed(2)}</span>
                {p.chapter && (
                  <Link to={`/read/${p.chapter.id}`} className="text-xs underline text-muted-foreground hover:text-foreground">
                    Read
                  </Link>
                )}
              </div>
            </div>
          ))}
        </div>
      )}
    </section>
  );
}
```

---

## `src/components/ReadingGoalTracker.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
import { Target, BookOpen, FileText } from 'lucide-react';

export default function ReadingGoalTracker() {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [goal, setGoal] = useState(null);
  const [targetType, setTargetType] = useState('chapters');
  const [dailyTarget, setDailyTarget] = useState(1);
  const [progress, setProgress] = useState({ chapters: 0, words: 0 });
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);

  const today = new Date().toISOString().slice(0, 10);

  const load = async () => {
    if (!user) return;
    try {
      const goals = await base44.entities.ReadingGoal.filter({ user_id: user.id });
      const g = goals[0];
      if (g) {
        setGoal(g);
        setTargetType(g.target_type);
        setDailyTarget(g.daily_target);
      }
      const todayLogs = await base44.entities.ReadingProgress.filter({ user_id: user.id, date: today });
      const chapters = todayLogs.length;
      const words = todayLogs.reduce((s, l) => s + (l.word_count || 0), 0);
      setProgress({ chapters, words });
    } catch {}
    setLoading(false);
  };

  useEffect(() => { load(); }, [user]);

  const save = async () => {
    setSaving(true);
    try {
      const target = Math.max(1, Number(dailyTarget) || 1);
      if (goal) {
        const updated = await base44.entities.ReadingGoal.update(goal.id, { target_type: targetType, daily_target: target });
        setGoal(updated);
      } else {
        const created = await base44.entities.ReadingGoal.create({ user_id: user.id, target_type: targetType, daily_target: target });
        setGoal(created);
      }
      setDailyTarget(target);
      toast({ title: 'Reading goal saved' });
    } catch (e) {
      toast({ title: 'Could not save goal', description: e.message, variant: 'destructive' });
    }
    setSaving(false);
  };

  if (!user) return null;

  const value = targetType === 'chapters' ? progress.chapters : progress.words;
  const target = Math.max(1, Number(dailyTarget) || 1);
  const pct = Math.min(100, Math.round((value / target) * 100));
  const done = value >= target;

  return (
    <section className="rounded-xl border border-border/60 p-5 space-y-4">
      <div className="flex items-center gap-2">
        <Target className="w-4 h-4" />
        <h2 className="font-heading text-lg font-semibold">Daily reading goal</h2>
      </div>

      {loading ? (
        <p className="text-sm text-muted-foreground">Loading…</p>
      ) : (
        <>
          <div>
            <div className="flex items-baseline justify-between mb-1.5">
              <p className="text-sm text-muted-foreground">Today's progress</p>
              <p className="text-sm font-medium">{value.toLocaleString()} / {target.toLocaleString()} {targetType === 'chapters' ? 'chapters' : 'words'}</p>
            </div>
            <div className="h-2.5 rounded-full bg-muted overflow-hidden">
              <div className={`h-full rounded-full transition-all ${done ? 'bg-emerald-500' : 'bg-primary'}`} style={{ width: `${pct}%` }} />
            </div>
            {done ? (
              <p className="text-xs text-emerald-600 mt-1.5">Goal reached — nice work! 🎉</p>
            ) : (
              <p className="text-xs text-muted-foreground mt-1.5">{target - value} {targetType === 'chapters' ? 'chapters' : 'words'} to go today.</p>
            )}
          </div>

          <div className="flex flex-wrap items-end gap-3 pt-1">
            <div>
              <Label className="text-xs">I want to read</Label>
              <div className="flex items-center gap-1.5 mt-1.5">
                <Button type="button" variant={targetType === 'chapters' ? 'default' : 'outline'} size="sm" className="rounded-full" onClick={() => setTargetType('chapters')}>
                  <BookOpen className="w-3.5 h-3.5 mr-1" /> Chapters
                </Button>
                <Button type="button" variant={targetType === 'words' ? 'default' : 'outline'} size="sm" className="rounded-full" onClick={() => setTargetType('words')}>
                  <FileText className="w-3.5 h-3.5 mr-1" /> Words
                </Button>
              </div>
            </div>
            <div>
              <Label className="text-xs">per day</Label>
              <Input type="number" min={1} value={dailyTarget} onChange={(e) => setDailyTarget(e.target.value)} className="mt-1.5 w-24" />
            </div>
            <Button onClick={save} disabled={saving} className="rounded-full">{saving ? 'Saving…' : 'Save goal'}</Button>
          </div>
        </>
      )}
    </section>
  );
}
```

---

## `src/components/ReferencesEditor.jsx`

```javascript
import { useState } from 'react';
import { base44 } from '@/api/base44Client';
import { Plus, Trash2, Link2 } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';

export default function ReferencesEditor({ references, onChange }) {
  const [query, setQuery] = useState('');
  const [results, setResults] = useState([]);
  const [activeRow, setActiveRow] = useState(null);

  const update = (i, field, value) => {
    const next = references.map((r, idx) => (idx === i ? { ...r, [field]: value } : r));
    onChange(next);
  };
  const add = () =>
    onChange([...references, { paper_id: '', title: '', authors: '', year: '', source: '', url: '' }]);
  const remove = (i) => onChange(references.filter((_, idx) => idx !== i));

  const search = async (q, i) => {
    setQuery(q);
    setActiveRow(i);
    if (q.trim().length < 2) {
      setResults([]);
      return;
    }
    try {
      const r = await base44.entities.ResearchPaper.filter({ status: 'published' }, '-created_date', 10);
      const lower = q.toLowerCase();
      setResults(r.filter((p) => p.id !== '' && p.title.toLowerCase().includes(lower)));
    } catch {
      setResults([]);
    }
  };

  const link = (i, paper) => {
    const next = references.map((r, idx) =>
      idx === i
        ? {
            ...r,
            paper_id: paper.id,
            title: paper.title,
            authors: (paper.authors || []).join(', '),
            year: paper.published_date ? new Date(paper.published_date).getFullYear().toString() : '',
            source: 'Chapterly',
          }
        : r
    );
    onChange(next);
    setResults([]);
    setQuery('');
    setActiveRow(null);
  };

  return (
    <div className="space-y-3">
      {references.map((ref, i) => (
        <div key={i} className="rounded-lg border border-border/60 p-3 space-y-2 relative">
          <div className="flex items-center justify-between">
            <span className="text-[11px] uppercase tracking-wide text-muted-foreground">Reference {i + 1}</span>
            <Button variant="ghost" size="sm" className="h-7 px-2 text-muted-foreground hover:text-destructive" onClick={() => remove(i)}>
              <Trash2 className="w-3.5 h-3.5" />
            </Button>
          </div>
          {ref.paper_id && (
            <span className="inline-flex items-center gap-1 text-[10px] px-1.5 py-0.5 rounded-full bg-primary/10 text-primary">
              <Link2 className="w-3 h-3" /> Linked to Chapterly paper
            </span>
          )}
          <Input
            placeholder="Search Chapterly papers to link…"
            value={activeRow === i ? query : ''}
            onChange={(e) => search(e.target.value, i)}
            className="h-8 text-sm"
          />
          {activeRow === i && results.length > 0 && (
            <div className="rounded-lg border border-border bg-popover max-h-40 overflow-auto">
              {results.map((p) => (
                <button
                  key={p.id}
                  onClick={() => link(i, p)}
                  className="block w-full text-left px-3 py-2 text-xs hover:bg-muted transition"
                >
                  <span className="font-medium">{p.title}</span>
                  <span className="text-muted-foreground"> · {(p.authors || []).join(', ')}</span>
                </button>
              ))}
            </div>
          )}
          <Input
            placeholder="Title"
            value={ref.title}
            onChange={(e) => update(i, 'title', e.target.value)}
            className="h-8 text-sm"
          />
          <Input
            placeholder="Authors (e.g. Smith, J.)"
            value={ref.authors}
            onChange={(e) => update(i, 'authors', e.target.value)}
            className="h-8 text-sm"
          />
          <div className="grid grid-cols-2 gap-2">
            <Input placeholder="Year" value={ref.year} onChange={(e) => update(i, 'year', e.target.value)} className="h-8 text-sm" />
            <Input placeholder="Source" value={ref.source} onChange={(e) => update(i, 'source', e.target.value)} className="h-8 text-sm" />
          </div>
          <Input
            placeholder="URL (optional)"
            value={ref.url}
            onChange={(e) => update(i, 'url', e.target.value)}
            className="h-8 text-sm"
          />
        </div>
      ))}
      <Button variant="outline" size="sm" onClick={add} className="rounded-full">
        <Plus className="w-3.5 h-3.5 mr-1.5" /> Add reference
      </Button>
    </div>
  );
}
```

---

## `src/components/ReportButton.jsx`

```javascript
import { useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Flag } from 'lucide-react';

export default function ReportButton({ targetType, targetId }) {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [open, setOpen] = useState(false);
  const [reason, setReason] = useState('');

  const submit = async () => {
    if (!user) return toast({ title: 'Sign in to report' });
    if (!reason.trim()) return;
    try {
      await base44.entities.Report.create({ reporter_id: user.id, target_type: targetType, target_id: targetId, reason: reason.trim(), status: 'open' });
      toast({ title: 'Report submitted', description: 'Our team will review it.' });
      setReason('');
      setOpen(false);
    } catch (e) {
      toast({ title: 'Failed', description: e.message, variant: 'destructive' });
    }
  };

  return (
    <div className="relative">
      <Button variant="ghost" size="sm" className="rounded-full text-muted-foreground" onClick={() => setOpen((v) => !v)}>
        <Flag className="w-3.5 h-3.5 mr-1.5" /> Report
      </Button>
      {open && (
        <div className="absolute right-0 mt-2 w-72 rounded-xl border border-border bg-popover shadow-lg z-50 p-3 space-y-2">
          <Textarea value={reason} onChange={(e) => setReason(e.target.value)} placeholder="What's the issue?" rows={3} className="text-sm" />
          <Button onClick={submit} size="sm" className="rounded-full w-full" disabled={!reason.trim()}>Submit report</Button>
        </div>
      )}
    </div>
  );
}
```

---

## `src/components/ResearchPaperCard.jsx`

```javascript
import { Link } from 'react-router-dom';
import { GraduationCap, Quote } from 'lucide-react';

export default function ResearchPaperCard({ paper, citationCount = 0 }) {
  return (
    <Link
      to={`/research/${paper.id}`}
      className="block rounded-xl border border-border/60 bg-card p-4 hover:shadow-sm transition"
    >
      <div className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
        <GraduationCap className="w-3.5 h-3.5" />
        <span>{paper.field || 'Research'}</span>
      </div>
      <h3 className="font-heading font-semibold text-sm mt-2 line-clamp-2">{paper.title}</h3>
      <p className="text-xs text-muted-foreground mt-1 line-clamp-1">
        {(paper.authors || []).join(', ') || 'Anonymous'}
      </p>
      {paper.keywords && paper.keywords.length > 0 && (
        <div className="flex flex-wrap gap-1 mt-2">
          {paper.keywords.slice(0, 3).map((k) => (
            <span key={k} className="text-[10px] px-1.5 py-0.5 rounded-full bg-muted text-muted-foreground">#{k}</span>
          ))}
        </div>
      )}
      <div className="flex items-center gap-3 mt-3 text-[11px] text-muted-foreground">
        {paper.citation_id && <span className="font-mono">{paper.citation_id}</span>}
        <span className="inline-flex items-center gap-1">
          <Quote className="w-3 h-3" /> {citationCount} cited
        </span>
      </div>
    </Link>
  );
}
```

---

## `src/components/RichTextEditor.jsx`

```javascript
import ReactQuill from 'react-quill-new';
import 'react-quill-new/dist/quill.snow.css';

const modules = {
  toolbar: [
    [{ header: [1, 2, 3, false] }],
    ['bold', 'italic', 'underline'],
    [{ list: 'ordered' }, { list: 'bullet' }],
    ['blockquote'],
    ['clean'],
  ],
};

export default function RichTextEditor({ value, onChange, placeholder }) {
  return (
    <ReactQuill
      theme="snow"
      value={value}
      onChange={onChange}
      modules={modules}
      placeholder={placeholder}
    />
  );
}
```

---

## `src/components/ScrollToTop.jsx`

```javascript
import { useEffect } from "react";
import { useLocation, useNavigationType } from "react-router-dom";

const getHashId = (hash) => {
  const rawId = hash.slice(1);

  try {
    return decodeURIComponent(rawId);
  } catch {
    return rawId;
  }
};

export default function ScrollToTop() {
  const { pathname, hash } = useLocation();
  const navigationType = useNavigationType();

  useEffect(() => {
    if (navigationType === "POP") return;

    if (hash) {
      const id = getHashId(hash);
      const timer = window.setTimeout(() => {
        document.getElementById(id)?.scrollIntoView({ behavior: "smooth" });
      }, 50);
      return () => window.clearTimeout(timer);
    }

    window.scrollTo({ top: 0, left: 0, behavior: "instant" });
  }, [pathname, hash, navigationType]);

  return null;
}

```

---

## `src/components/ShareButtons.jsx`

```javascript
import { useState } from 'react';
import { Twitter, Facebook, MessageCircle, Link2, Share2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import VisualShareCard from '@/components/VisualShareCard';

// Reusable social share row: X, Facebook, WhatsApp, copy link, and native share sheet (mobile).
export default function ShareButtons({ url, title, text, className, card }) {
  const { toast } = useToast();
  const [copied, setCopied] = useState(false);
  const shareUrl = url || (typeof window !== 'undefined' ? window.location.href : '');
  const shareText = text || title || '';
  const encUrl = encodeURIComponent(shareUrl);
  const encText = encodeURIComponent(shareText);

  const links = {
    twitter: `https://twitter.com/intent/tweet?text=${encText}&url=${encUrl}`,
    facebook: `https://www.facebook.com/sharer/sharer.php?u=${encUrl}`,
    whatsapp: `https://wa.me/?text=${encodeURIComponent(`${shareText} ${shareUrl}`)}`,
  };

  const open = (href) => window.open(href, '_blank', 'noopener,noreferrer,width=600,height=600');

  const copyLink = async () => {
    try {
      await navigator.clipboard.writeText(shareUrl);
      setCopied(true);
      toast({ title: 'Link copied to clipboard' });
      setTimeout(() => setCopied(false), 2000);
    } catch {
      toast({ title: 'Could not copy link', variant: 'destructive' });
    }
  };

  const nativeShare = async () => {
    if (navigator.share) {
      try { await navigator.share({ title: shareText || 'Chapterly', url: shareUrl }); } catch {}
    } else {
      copyLink();
    }
  };

  const btn = 'h-9 w-9 rounded-full p-0';

  return (
    <div className={`flex items-center gap-2 ${className || ''}`}>
      <Button variant="outline" size="icon" className={btn} onClick={() => open(links.twitter)} aria-label="Share on X">
        <Twitter className="w-4 h-4" />
      </Button>
      <Button variant="outline" size="icon" className={btn} onClick={() => open(links.facebook)} aria-label="Share on Facebook">
        <Facebook className="w-4 h-4" />
      </Button>
      <Button variant="outline" size="icon" className={btn} onClick={() => open(links.whatsapp)} aria-label="Share on WhatsApp">
        <MessageCircle className="w-4 h-4" />
      </Button>
      <Button variant="outline" size="icon" className={btn} onClick={copyLink} aria-label="Copy link">
        <Link2 className="w-4 h-4" />
      </Button>
      {typeof navigator !== 'undefined' && navigator.share && (
        <Button variant="outline" size="icon" className={btn} onClick={nativeShare} aria-label="Share via…">
          <Share2 className="w-4 h-4" />
        </Button>
      )}
      {card && <VisualShareCard {...card} url={shareUrl} />}
      {copied && <span className="text-xs text-muted-foreground">Copied!</span>}
    </div>
  );
}
```

---

## `src/components/SharePaperButton.jsx`

```javascript
import { useState } from 'react';
import { Share2, Link2, Twitter, Facebook, Linkedin, Mail, Download, Check, Loader2 } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, DropdownMenuSeparator } from '@/components/ui/dropdown-menu';
import { downloadPaperPdf } from '@/lib/paperPdf';
import { SITE } from '@/lib/citations';

export default function SharePaperButton({ paper }) {
  const [copied, setCopied] = useState(false);
  const [downloading, setDownloading] = useState(false);
  const url = `${SITE}/research/${paper.id}`;
  const shareText = `${paper.title} — on Chapterly`;

  const nativeShare = async () => {
    if (navigator.share) {
      try { await navigator.share({ title: paper.title, text: shareText, url }); } catch {}
    }
  };

  const copyLink = () => {
    navigator.clipboard.writeText(url);
    setCopied(true);
    setTimeout(() => setCopied(false), 1500);
  };

  const handleDownload = async () => {
    setDownloading(true);
    try { await downloadPaperPdf(paper); } finally { setDownloading(false); }
  };

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button className="rounded-full">
          <Share2 className="w-4 h-4 mr-1.5" /> Share
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent align="end" className="w-52">
        {typeof navigator !== 'undefined' && navigator.share && (
          <DropdownMenuItem onClick={nativeShare}>
            <Share2 className="w-4 h-4 mr-2" /> Share via device…
          </DropdownMenuItem>
        )}
        <DropdownMenuItem onClick={copyLink}>
          {copied ? <Check className="w-4 h-4 mr-2" /> : <Link2 className="w-4 h-4 mr-2" />}
          {copied ? 'Link copied' : 'Copy link'}
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem asChild>
          <a href={`https://twitter.com/intent/tweet?text=${encodeURIComponent(shareText)}&url=${encodeURIComponent(url)}`} target="_blank" rel="noreferrer" className="flex items-center">
            <Twitter className="w-4 h-4 mr-2" /> X / Twitter
          </a>
        </DropdownMenuItem>
        <DropdownMenuItem asChild>
          <a href={`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)}`} target="_blank" rel="noreferrer" className="flex items-center">
            <Facebook className="w-4 h-4 mr-2" /> Facebook
          </a>
        </DropdownMenuItem>
        <DropdownMenuItem asChild>
          <a href={`https://www.linkedin.com/sharing/share-offsite/?url=${encodeURIComponent(url)}`} target="_blank" rel="noreferrer" className="flex items-center">
            <Linkedin className="w-4 h-4 mr-2" /> LinkedIn
          </a>
        </DropdownMenuItem>
        <DropdownMenuItem asChild>
          <a href={`mailto:?subject=${encodeURIComponent(paper.title)}&body=${encodeURIComponent(shareText + '\n\n' + url)}`} className="flex items-center">
            <Mail className="w-4 h-4 mr-2" /> Email
          </a>
        </DropdownMenuItem>
        <DropdownMenuSeparator />
        <DropdownMenuItem onClick={handleDownload} disabled={downloading}>
          {downloading ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : <Download className="w-4 h-4 mr-2" />}
          Download PDF
        </DropdownMenuItem>
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
```

---

## `src/components/SmartAppBanner.jsx`

```javascript
import { useEffect, useState } from 'react';
import { X, Download } from 'lucide-react';

const DISMISS_KEY = 'chapterly_app_banner_dismissed';

// Replace these with your actual store listing URLs once the apps are published
const APP_STORE_URL = 'https://apps.apple.com/app/chapterly/idAPP_STORE_ID';
const PLAY_STORE_URL = 'https://play.google.com/store/apps/details?id=com.baseAPPID.app';

export default function SmartAppBanner() {
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const dismissed = localStorage.getItem(DISMISS_KEY);
    if (!dismissed) setVisible(true);
  }, []);

  const handleDismiss = () => {
    localStorage.setItem(DISMISS_KEY, '1');
    setVisible(false);
  };

  if (!visible) return null;

  const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream;
  const storeUrl = isIOS ? APP_STORE_URL : PLAY_STORE_URL;

  return (
    <div className="fixed top-0 left-0 right-0 z-50 bg-primary text-primary-foreground safe-top">
      <div className="mx-auto max-w-6xl px-4 h-14 flex items-center gap-3">
        <div className="w-9 h-9 rounded-lg bg-primary-foreground/15 flex items-center justify-center shrink-0">
          <span className="text-lg">📖</span>
        </div>
        <div className="flex-1 min-w-0">
          <p className="text-sm font-semibold leading-tight">Chapterly</p>
          <p className="text-xs opacity-80 leading-tight truncate">Get the app for the best reading experience</p>
        </div>
        <a
          href={storeUrl}
          target="_blank"
          rel="noopener noreferrer"
          className="inline-flex items-center gap-1.5 rounded-full bg-primary-foreground text-primary px-4 py-1.5 text-sm font-medium shrink-0"
        >
          <Download className="w-3.5 h-3.5" />
          Get
        </a>
        <button
          onClick={handleDismiss}
          className="p-1.5 rounded-full hover:bg-primary-foreground/10 transition shrink-0"
          aria-label="Dismiss"
        >
          <X className="w-4 h-4" />
        </button>
      </div>
    </div>
  );
}
```

---

## `src/components/StoryCard.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { Image } from '@/components/ui/image';
import { getPublicProfile } from '@/lib/publicProfiles';
import { Heart } from 'lucide-react';

export default function StoryCard({ story, likeCount }) {
  const [author, setAuthor] = useState(null);

  useEffect(() => {
    let active = true;
    getPublicProfile(story.created_by_id)
      .then((u) => active && setAuthor(u))
      .catch(() => {});
    return () => { active = false; };
  }, [story.created_by_id]);

  return (
    <Link to={`/story/${story.id}`} className="group block">
      <div className="aspect-[3/4] rounded-xl overflow-hidden bg-muted ring-1 ring-border/60 relative">
        {story.cover_url ? (
          <Image
            src={story.cover_url}
            fittingType="fill"
            className="w-full h-full transition-transform duration-300 group-hover:scale-[1.04]"
          />
        ) : (
          <div className="w-full h-full flex items-center justify-center p-3 text-center">
            <span className="font-heading text-sm font-medium text-muted-foreground line-clamp-3">
              {story.title}
            </span>
          </div>
        )}
        {likeCount > 0 && (
          <span className="absolute top-2 right-2 inline-flex items-center gap-1 rounded-full bg-background/85 backdrop-blur px-1.5 py-0.5 text-[11px] font-medium text-foreground shadow-sm">
            <Heart className="w-3 h-3 fill-current text-rose-500" /> {likeCount}
          </span>
        )}
      </div>
      <div className="mt-2.5">
        <h3 className="font-heading font-semibold text-sm leading-snug line-clamp-2 group-hover:underline underline-offset-2">
          {story.title}
        </h3>
        <p className="text-xs text-muted-foreground mt-0.5">
          by {author?.display_name || author?.full_name || 'Unknown'}
        </p>
        <div className="flex flex-wrap items-center gap-1.5 mt-1.5">
          <span className="inline-block text-[11px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground">
            {story.genre}
          </span>
          {story.sub_genre && (
            <span className="inline-block text-[11px] px-1.5 py-0.5 rounded bg-secondary text-secondary-foreground">
              {story.sub_genre}
            </span>
          )}
        </div>
      </div>
    </Link>
  );
}
```

---

## `src/components/StoryRating.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/components/ui/use-toast';
import StarPicker from '@/components/reviews/StarPicker';

export default function StoryRating({ storyId }) {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [ratings, setRatings] = useState([]);
  const [mine, setMine] = useState(0);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const all = await base44.entities.Rating.filter({ story_id: storyId });
        if (!active) return;
        setRatings(all);
        if (user) {
          const my = all.find((r) => r.user_id === user.id);
          setMine(my ? my.value : 0);
        }
      } catch {}
    })();
    return () => { active = false; };
  }, [storyId, user]);

  const avg = ratings.length ? ratings.reduce((s, r) => s + r.value, 0) / ratings.length : 0;
  const count = ratings.length;

  const submit = async (v) => {
    if (!user) return toast({ title: 'Sign in to rate stories' });
    if (saving) return;
    setSaving(true);
    try {
      if (mine) {
        const rec = ratings.find((r) => r.user_id === user.id);
        if (rec) await base44.entities.Rating.update(rec.id, { value: v });
        setRatings((prev) => prev.map((r) => (r.user_id === user.id ? { ...r, value: v } : r)));
      } else {
        const rec = await base44.entities.Rating.create({ user_id: user.id, story_id: storyId, value: v });
        setRatings((prev) => [...prev, rec]);
      }
      setMine(v);
    } catch (e) {
      toast({ title: 'Could not save rating', description: e.message, variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  return (
    <div className="flex items-center gap-3">
      <StarPicker value={mine} onChange={submit} disabled={!user || saving} />
      <span className="text-sm text-muted-foreground">
        {count > 0 ? (
          <><span className="font-medium text-foreground">{avg.toFixed(1)}</span> · {count} {count === 1 ? 'rating' : 'ratings'}</>
        ) : (
          'No ratings yet'
        )}
      </span>
      {mine > 0 && <span className="text-xs text-muted-foreground">· You rated {mine}</span>}
    </div>
  );
}
```

---

## `src/components/TipButton.jsx`

```javascript
import { useState } from 'react';
import { base44 } from '@/api/base44Client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { useToast } from '@/components/ui/use-toast';
import { Heart, Loader2 } from 'lucide-react';

const PRESETS = [1, 3, 5, 10];

export default function TipButton({ writerId, writerName, chapterId }) {
  const { toast } = useToast();
  const [open, setOpen] = useState(false);
  const [amount, setAmount] = useState(3);
  const [custom, setCustom] = useState('');
  const [loading, setLoading] = useState(false);

  const finalAmount = custom ? Number(custom) : amount;

  const tip = async () => {
    if (!finalAmount || finalAmount < 0.5) {
      toast({ title: 'Enter at least $0.50', variant: 'destructive' });
      return;
    }
    if (window.self !== window.top) {
      toast({ title: 'Checkout unavailable in preview', description: 'Open the published app to tip.', variant: 'destructive' });
      return;
    }
    setLoading(true);
    try {
      const res = await base44.functions.invoke('createCheckout', { type: 'tip', writerId, chapterId, amount: finalAmount });
      if (res.data?.url) window.location.href = res.data.url;
      else toast({ title: 'Could not start checkout', description: res.data?.error, variant: 'destructive' });
    } catch (e) {
      toast({ title: 'Tip failed', description: e.message, variant: 'destructive' });
    } finally {
      setLoading(false);
    }
  };

  return (
    <Dialog open={open} onOpenChange={setOpen}>
      <DialogTrigger asChild>
        <Button variant="outline" size="sm" className="rounded-full">
          <Heart className="w-4 h-4 mr-1.5" /> Tip
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>Support {writerName || 'this writer'}</DialogTitle>
        </DialogHeader>
        <p className="text-sm text-muted-foreground">
          Send a one-time tip to show your appreciation for their stories.
        </p>
        <div className="grid grid-cols-4 gap-2 mt-3">
          {PRESETS.map((p) => (
            <Button
              key={p}
              variant={amount === p && !custom ? 'default' : 'outline'}
              onClick={() => { setAmount(p); setCustom(''); }}
            >
              ${p}
            </Button>
          ))}
        </div>
        <div className="mt-3">
          <Input
            type="number"
            min="0.5"
            step="0.5"
            placeholder="Custom amount"
            value={custom}
            onChange={(e) => setCustom(e.target.value)}
          />
        </div>
        <Button onClick={tip} disabled={loading || !finalAmount} className="w-full rounded-full mt-4">
          {loading ? <Loader2 className="w-4 h-4 animate-spin" /> : <Heart className="w-4 h-4 mr-1.5" />}
          {loading ? 'Redirecting…' : `Tip $${(finalAmount || 0).toFixed(2)}`}
        </Button>
      </DialogContent>
    </Dialog>
  );
}
```

---

## `src/components/UserNotRegisteredError.jsx`

```javascript
import React from 'react';

const UserNotRegisteredError = () => {
  return (
    <div className="flex flex-col items-center justify-center min-h-screen bg-gradient-to-b from-white to-slate-50">
      <div className="max-w-md w-full p-8 bg-white rounded-lg shadow-lg border border-slate-100">
        <div className="text-center">
          <div className="inline-flex items-center justify-center w-16 h-16 mb-6 rounded-full bg-orange-100">
            <svg className="w-8 h-8 text-orange-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
          </div>
          <h1 className="text-3xl font-bold text-slate-900 mb-4">Access Restricted</h1>
          <p className="text-slate-600 mb-8">
            You are not registered to use this application. Please contact the app administrator to request access.
          </p>
          <div className="p-4 bg-slate-50 rounded-md text-sm text-slate-600">
            <p>If you believe this is an error, you can:</p>
            <ul className="list-disc list-inside mt-2 space-y-1">
              <li>Verify you are logged in with the correct account</li>
              <li>Contact the app administrator for access</li>
              <li>Try logging out and back in again</li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  );
};

export default UserNotRegisteredError;

```

---

## `src/components/VisualShareCard.jsx`

```javascript
import { useRef, useState } from 'react';
import html2canvas from 'html2canvas';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { useToast } from '@/components/ui/use-toast';
import { Image as ImageIcon, Download, Share2, Loader2 } from 'lucide-react';

// Renders a polished share card (cover art + title + author + Chapterly branding),
// captures it to a PNG via html2canvas, and lets the reader download or share the image.
export default function VisualShareCard({ title, author, coverUrl, genre, url }) {
  const cardRef = useRef(null);
  const [open, setOpen] = useState(false);
  const [imgUrl, setImgUrl] = useState(null);
  const [busy, setBusy] = useState(false);
  const { toast } = useToast();

  const shareUrl = url || (typeof window !== 'undefined' ? window.location.href : '');
  const displayHost = shareUrl.replace(/^https?:\/\//, '').split('/')[0];

  const generate = async () => {
    setBusy(true);
    setImgUrl(null);
    setOpen(true);
    // Allow the dialog + off-screen card images to paint before capture.
    await new Promise((r) => setTimeout(r, 200));
    try {
      const canvas = await html2canvas(cardRef.current, {
        scale: 2,
        useCORS: true,
        backgroundColor: '#0f172a',
        logging: false,
      });
      setImgUrl(canvas.toDataURL('image/png'));
    } catch (e) {
      toast({ title: 'Could not generate card', description: e.message, variant: 'destructive' });
      setOpen(false);
    } finally {
      setBusy(false);
    }
  };

  const download = () => {
    if (!imgUrl) return;
    const a = document.createElement('a');
    a.href = imgUrl;
    a.download = `${(title || 'chapterly').toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40)}-share.png`;
    document.body.appendChild(a);
    a.click();
    a.remove();
  };

  const nativeShare = async () => {
    if (!imgUrl) return;
    try {
      const res = await fetch(imgUrl);
      const blob = await res.blob();
      const file = new File([blob], 'chapterly-share.png', { type: 'image/png' });
      if (navigator.canShare && navigator.canShare({ files: [file] })) {
        await navigator.share({
          files: [file],
          title: title || 'Chapterly',
          text: `${title} by ${author || 'an indie writer'} on Chapterly`,
        });
      } else if (navigator.share) {
        await navigator.share({ title: title || 'Chapterly', text: `${title} by ${author || 'an indie writer'}`, url: shareUrl });
      } else {
        download();
      }
    } catch {
      /* user cancelled */
    }
  };

  return (
    <>
      <Button variant="outline" size="icon" className="h-9 w-9 rounded-full p-0" onClick={generate} aria-label="Create share card">
        <ImageIcon className="w-4 h-4" />
      </Button>

      {/* Off-screen capture node — always mounted so cover images preload before capture. */}
      <div style={{ position: 'fixed', left: '-99999px', top: 0, pointerEvents: 'none' }} aria-hidden="true">
        <div
          ref={cardRef}
          style={{
            width: 540,
            height: 675,
            borderRadius: 24,
            overflow: 'hidden',
            position: 'relative',
            background: 'linear-gradient(160deg, #1e293b 0%, #0f172a 100%)',
            fontFamily: 'ui-sans-serif, system-ui, -apple-system, sans-serif',
            color: '#ffffff',
          }}
        >
          <div style={{ position: 'absolute', top: -70, right: -70, width: 240, height: 240, borderRadius: '50%', background: 'radial-gradient(circle, rgba(59,130,246,0.55), transparent 70%)' }} />
          <div style={{ position: 'absolute', bottom: -90, left: -90, width: 260, height: 260, borderRadius: '50%', background: 'radial-gradient(circle, rgba(45,212,191,0.35), transparent 70%)' }} />

          <div style={{ position: 'relative', padding: 36, display: 'flex', gap: 26, height: '100%', boxSizing: 'border-box' }}>
            <div
              style={{
                width: 196,
                height: 268,
                borderRadius: 12,
                overflow: 'hidden',
                boxShadow: '0 14px 34px rgba(0,0,0,0.45)',
                flexShrink: 0,
                background: '#334155',
              }}
            >
              {coverUrl ? (
                <img src={coverUrl} crossOrigin="anonymous" alt="" style={{ width: '100%', height: '100%', objectFit: 'cover', display: 'block' }} />
              ) : (
                <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', padding: 14, textAlign: 'center', fontSize: 15, fontWeight: 600, color: '#cbd5e1' }}>
                  {title}
                </div>
              )}
            </div>
            <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', minWidth: 0 }}>
              {genre && (
                <span style={{ fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase', color: '#7dd3fc', marginBottom: 10, fontWeight: 600 }}>
                  {genre}
                </span>
              )}
              <h1 style={{ fontSize: 30, fontWeight: 700, lineHeight: 1.15, marginBottom: 14, display: '-webkit-box', WebkitLineClamp: 4, WebkitBoxOrient: 'vertical', overflow: 'hidden' }}>
                {title}
              </h1>
              <p style={{ fontSize: 16, color: '#cbd5e1' }}>by {author || 'Unknown'}</p>
            </div>
          </div>

          <div
            style={{
              position: 'absolute',
              bottom: 0,
              left: 0,
              right: 0,
              padding: '22px 36px',
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
              borderTop: '1px solid rgba(255,255,255,0.12)',
              background: 'rgba(15,23,42,0.4)',
            }}
          >
            <div>
              <p style={{ fontSize: 11, color: '#94a3b8', marginBottom: 2 }}>Read it on</p>
              <p style={{ fontSize: 22, fontWeight: 700, letterSpacing: -0.5 }}>Chapterly</p>
            </div>
            <div style={{ fontSize: 12, color: '#94a3b8', textAlign: 'right', maxWidth: 190, wordBreak: 'break-all' }}>
              {displayHost}
            </div>
          </div>
        </div>
      </div>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent className="max-w-md">
          <DialogHeader>
            <DialogTitle>Share card</DialogTitle>
            <DialogDescription>Save or share this image to spread the word about this story.</DialogDescription>
          </DialogHeader>
          {busy ? (
            <div className="flex items-center justify-center h-72">
              <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
            </div>
          ) : imgUrl ? (
            <div className="space-y-4">
              <img src={imgUrl} alt={`${title} share card`} className="w-full rounded-xl border border-border/60" />
              <div className="flex gap-2">
                <Button onClick={download} className="rounded-full flex-1">
                  <Download className="w-4 h-4 mr-1.5" /> Download
                </Button>
                <Button onClick={nativeShare} variant="outline" className="rounded-full flex-1">
                  <Share2 className="w-4 h-4 mr-1.5" /> Share
                </Button>
              </div>
            </div>
          ) : null}
        </DialogContent>
      </Dialog>
    </>
  );
}
```

---

## `src/components/WeeklyLeaderboard.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { MessageSquare, Coins, Crown, Trophy } from 'lucide-react';

export default function WeeklyLeaderboard() {
  const [data, setData] = useState({ readers: [], contributors: [] });
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    (async () => {
      try {
        const res = await base44.functions.invoke('getWeeklyLeaderboard', {});
        if (res.data) setData(res.data);
      } catch {}
      setLoading(false);
    })();
  }, []);

  if (loading) return <p className="text-sm text-muted-foreground">Loading leaderboard…</p>;

  const renderRow = (rank, item, subtitle) => (
    <div key={item.id} className="flex items-center gap-3 py-2.5 border-b border-border/40 last:border-0">
      <span className={`w-6 text-center text-sm font-semibold ${rank <= 3 ? 'text-primary' : 'text-muted-foreground'}`}>{rank}</span>
      <Avatar className="w-8 h-8">
        <AvatarImage src={item.avatar_url} />
        <AvatarFallback>{(item.name || '?')[0]}</AvatarFallback>
      </Avatar>
      <div className="flex-1 min-w-0">
        <p className="text-sm font-medium truncate">{item.name}</p>
        <p className="text-xs text-muted-foreground">{subtitle}</p>
      </div>
    </div>
  );

  return (
    <div className="grid sm:grid-cols-2 gap-6">
      <section className="rounded-xl border border-border/60 p-5">
        <h2 className="font-heading text-lg font-semibold flex items-center gap-2 mb-1">
          <Trophy className="w-4 h-4" /> Most active readers
          <span className="text-xs font-normal text-muted-foreground">this week</span>
        </h2>
        {data.readers.length === 0 ? (
          <p className="text-sm text-muted-foreground py-4">No reader activity yet this week.</p>
        ) : (
          data.readers.map((r, i) => renderRow(
            i + 1,
            r,
            <span className="inline-flex items-center gap-3">
              <span className="inline-flex items-center gap-1"><Coins className="w-3 h-3" /> {r.tips} tips</span>
              <span className="inline-flex items-center gap-1"><MessageSquare className="w-3 h-3" /> {r.comments} comments</span>
            </span>
          ))
        )}
      </section>

      <section className="rounded-xl border border-border/60 p-5">
        <h2 className="font-heading text-lg font-semibold flex items-center gap-2 mb-1">
          <Crown className="w-4 h-4" /> Top contributors
          <span className="text-xs font-normal text-muted-foreground">this week</span>
        </h2>
        {data.contributors.length === 0 ? (
          <p className="text-sm text-muted-foreground py-4">No tips received yet this week.</p>
        ) : (
          data.contributors.map((w, i) => renderRow(
            i + 1,
            w,
            <span className="inline-flex items-center gap-3">
              <span className="inline-flex items-center gap-1"><Coins className="w-3 h-3" /> {w.tips} tips</span>
              <span>${(w.amount || 0).toFixed(2)} received</span>
            </span>
          ))
        )}
      </section>
    </div>
  );
}
```

---

## `src/components/WordCountProgress.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { BarChart, Bar, XAxis, Tooltip, ResponsiveContainer } from 'recharts';
import { PenLine, TrendingUp } from 'lucide-react';

const DAY_MS = 86400000;
const ymd = (d) => d.toISOString().slice(0, 10);

export default function WordCountProgress() {
  const { user } = useCurrentUser();
  const [days, setDays] = useState([]);
  const [breakdown, setBreakdown] = useState([]);
  const [total14, setTotal14] = useState(0);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!user) return;
    let active = true;
    (async () => {
      try {
        await base44.functions.invoke('logDailyWordCount', {});
        const logs = await base44.entities.WordCountLog.filter({ created_by_id: user.id }, '-date', 30);

        const map = {};
        logs.forEach((l) => { map[l.date] = l.words; });
        const sorted = [...logs].sort((a, b) => a.date.localeCompare(b.date));

        const today = new Date();
        const startStr = ymd(new Date(today.getTime() - 13 * DAY_MS));
        const anchor = sorted.filter((l) => l.date < startStr).pop();
        let prev = anchor ? anchor.words : 0;

        const arr = [];
        let sum = 0;
        for (let i = 13; i >= 0; i--) {
          const ds = ymd(new Date(today.getTime() - i * DAY_MS));
          let written = 0;
          if (map[ds] !== undefined) {
            written = Math.max(0, map[ds] - prev);
            prev = map[ds];
          }
          sum += written;
          arr.push({ date: ds, label: ds.slice(5), words: written });
        }
        if (!active) return;
        setDays(arr);
        setTotal14(sum);

        const stories = await base44.entities.Story.filter({ created_by_id: user.id });
        const rows = [];
        for (const s of stories) {
          const chapters = await base44.entities.Chapter.filter({ story_id: s.id });
          const words = chapters.reduce((n, c) => n + (c.word_count || 0), 0);
          rows.push({ id: s.id, title: s.title, words });
        }
        rows.sort((a, b) => b.words - a.words);
        if (active) setBreakdown(rows);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  const maxStory = Math.max(1, ...breakdown.map((r) => r.words));

  return (
    <div className="grid md:grid-cols-2 gap-4">
      <div className="rounded-2xl border border-border/60 p-5">
        <div className="flex items-center justify-between mb-1">
          <h3 className="font-heading font-semibold flex items-center gap-2"><TrendingUp className="w-4 h-4" /> Daily words</h3>
          <span className="text-xs text-muted-foreground">Last 14 days</span>
        </div>
        <p className="text-2xl font-semibold mb-3">{total14.toLocaleString()} <span className="text-sm font-normal text-muted-foreground">words written</span></p>
        {loading ? (
          <div className="h-40 flex items-center justify-center text-sm text-muted-foreground">Loading…</div>
        ) : (
          <ResponsiveContainer width="100%" height={160}>
            <BarChart data={days} margin={{ top: 4, right: 4, bottom: 0, left: -20 }}>
              <XAxis dataKey="label" tick={{ fontSize: 10 }} interval={1} tickLine={false} axisLine={false} />
              <Tooltip cursor={{ fill: 'hsl(var(--muted))' }} formatter={(v) => [`${v} words`, 'Written']} />
              <Bar dataKey="words" radius={[4, 4, 0, 0]} fill="hsl(var(--primary))" />
            </BarChart>
          </ResponsiveContainer>
        )}
      </div>

      <div className="rounded-2xl border border-border/60 p-5">
        <h3 className="font-heading font-semibold flex items-center gap-2 mb-3"><PenLine className="w-4 h-4" /> Words by story</h3>
        {loading ? (
          <div className="h-40 flex items-center justify-center text-sm text-muted-foreground">Loading…</div>
        ) : breakdown.length === 0 ? (
          <p className="text-sm text-muted-foreground">No stories yet.</p>
        ) : (
          <div className="space-y-3">
            {breakdown.map((r) => (
              <div key={r.id}>
                <div className="flex justify-between text-sm mb-1">
                  <span className="truncate pr-2">{r.title}</span>
                  <span className="text-muted-foreground shrink-0">{r.words.toLocaleString()}</span>
                </div>
                <div className="h-2 rounded-full bg-muted overflow-hidden">
                  <div className="h-full bg-primary rounded-full" style={{ width: `${(r.words / maxStory) * 100}%` }} />
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
```

---

## `src/components/WriterAnalytics.jsx`

```javascript
import { useMemo } from 'react';
import { Link } from 'react-router-dom';
import { Eye, Users, Heart, MessageSquare, TrendingUp } from 'lucide-react';
import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid } from 'recharts';
import { Image } from '@/components/ui/image';

export default function WriterAnalytics({ stories, stats, engagement }) {
  // Aggregate totals across all stories
  const totals = useMemo(() => {
    return stories.reduce(
      (acc, s) => {
        const st = stats[s.id] || {};
        acc.views += st.views || 0;
        acc.likes += st.likes || 0;
        acc.comments += st.comments || 0;
        return acc;
      },
      { views: 0, likes: 0, comments: 0 }
    );
  }, [stories, stats]);

  // Followers is writer-level — same value across all stories
  const followerCount = stats[stories[0]?.id]?.followers || 0;

  // Top performing stories ranked by views
  const topStories = useMemo(() => {
    return stories
      .map((story) => ({ story, stat: stats[story.id] || {} }))
      .filter((x) => (x.stat.views || 0) > 0)
      .sort((a, b) => (b.stat.views || 0) - (a.stat.views || 0))
      .slice(0, 5);
  }, [stories, stats]);

  const maxViews = topStories.length > 0 ? topStories[0].stat.views || 1 : 1;

  // Daily engagement trend (last 14 days)
  const trendData = useMemo(() => {
    const days = [];
    const now = new Date();
    for (let i = 13; i >= 0; i--) {
      const d = new Date(now);
      d.setDate(d.getDate() - i);
      d.setHours(0, 0, 0, 0);
      days.push({
        ts: d.getTime(),
        label: d.toLocaleDateString('en', { month: 'short', day: 'numeric' }),
        Likes: 0,
        Comments: 0,
        Follows: 0,
      });
    }
    const addToDay = (records, field) => {
      records.forEach((r) => {
        if (!r.created_date) return;
        const d = new Date(r.created_date);
        d.setHours(0, 0, 0, 0);
        const day = days.find((dd) => dd.ts === d.getTime());
        if (day) day[field]++;
      });
    };
    addToDay(engagement.likes, 'Likes');
    addToDay(engagement.comments, 'Comments');
    addToDay(engagement.follows, 'Follows');
    return days.map(({ label, Likes, Comments, Follows }) => ({
      label,
      Likes,
      Comments,
      Follows,
      Engagement: Likes + Comments + Follows,
    }));
  }, [engagement]);

  const hasEngagement = trendData.some((d) => d.Engagement > 0);

  const statCards = [
    { icon: Eye, label: 'Total views', value: totals.views, color: 'text-blue-500', bg: 'bg-blue-500/10' },
    { icon: Users, label: 'Followers', value: followerCount, color: 'text-emerald-500', bg: 'bg-emerald-500/10' },
    { icon: Heart, label: 'Likes', value: totals.likes, color: 'text-rose-500', bg: 'bg-rose-500/10' },
    { icon: MessageSquare, label: 'Comments', value: totals.comments, color: 'text-amber-500', bg: 'bg-amber-500/10' },
  ];

  return (
    <div className="space-y-6">
      {/* Summary stat cards */}
      <div className="grid grid-cols-2 lg:grid-cols-4 gap-4">
        {statCards.map((card) => (
          <div key={card.label} className="rounded-2xl border border-border/60 bg-card p-4">
            <div className={`w-10 h-10 rounded-full ${card.bg} ${card.color} flex items-center justify-center mb-3`}>
              <card.icon className="w-5 h-5" />
            </div>
            <div className="text-2xl font-heading font-semibold">{card.value.toLocaleString()}</div>
            <div className="text-sm text-muted-foreground">{card.label}</div>
          </div>
        ))}
      </div>

      {/* Reader activity trend chart */}
      <div className="rounded-2xl border border-border/60 bg-card p-5">
        <div className="flex items-center gap-2 mb-4">
          <TrendingUp className="w-4 h-4 text-primary" />
          <h2 className="font-heading font-semibold">Reader activity (14 days)</h2>
        </div>
        {hasEngagement ? (
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={trendData} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
              <defs>
                <linearGradient id="engagementGradient" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="hsl(var(--primary))" stopOpacity={0.3} />
                  <stop offset="95%" stopColor="hsl(var(--primary))" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
              <XAxis
                dataKey="label"
                tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
                tickLine={false}
                axisLine={false}
                interval="preserveStartEnd"
              />
              <YAxis
                tick={{ fontSize: 11, fill: 'hsl(var(--muted-foreground))' }}
                tickLine={false}
                axisLine={false}
                allowDecimals={false}
              />
              <Tooltip
                contentStyle={{
                  background: 'hsl(var(--card))',
                  border: '1px solid hsl(var(--border))',
                  borderRadius: '0.5rem',
                  fontSize: 12,
                }}
                labelStyle={{ color: 'hsl(var(--foreground))' }}
              />
              <Area
                type="monotone"
                dataKey="Engagement"
                stroke="hsl(var(--primary))"
                strokeWidth={2}
                fill="url(#engagementGradient)"
              />
            </AreaChart>
          </ResponsiveContainer>
        ) : (
          <div className="h-[200px] flex items-center justify-center text-sm text-muted-foreground">
            No reader activity in the last 14 days yet.
          </div>
        )}
      </div>

      {/* Top performing stories */}
      {topStories.length > 0 && (
        <div className="rounded-2xl border border-border/60 bg-card p-5">
          <h2 className="font-heading font-semibold mb-4">Top performing stories</h2>
          <div className="space-y-3">
            {topStories.map((item, idx) => (
              <Link
                key={item.story.id}
                to={`/dashboard/story/${item.story.id}`}
                className="flex items-center gap-3 group"
              >
                <span className="text-lg font-heading font-semibold text-muted-foreground w-6 text-center shrink-0">
                  {idx + 1}
                </span>
                <div className="w-10 h-14 rounded-md overflow-hidden bg-muted shrink-0">
                  {item.story.cover_url ? (
                    <Image src={item.story.cover_url} fittingType="fill" className="w-full h-full" />
                  ) : null}
                </div>
                <div className="flex-1 min-w-0">
                  <h3 className="font-medium truncate group-hover:text-primary transition">{item.story.title}</h3>
                  <div className="flex items-center gap-3 text-xs text-muted-foreground mt-0.5">
                    <span className="flex items-center gap-1">
                      <Eye className="w-3 h-3" /> {item.stat.views || 0}
                    </span>
                    <span className="flex items-center gap-1">
                      <Heart className="w-3 h-3" /> {item.stat.likes || 0}
                    </span>
                    <span className="flex items-center gap-1">
                      <MessageSquare className="w-3 h-3" /> {item.stat.comments || 0}
                    </span>
                  </div>
                  <div className="mt-1.5 h-1 rounded-full bg-muted overflow-hidden">
                    <div
                      className="h-full rounded-full bg-primary transition-all"
                      style={{ width: `${((item.stat.views || 0) / maxViews) * 100}%` }}
                    />
                  </div>
                </div>
              </Link>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}
```

---

## `src/components/WriterEarningsDashboard.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { PieChart, Pie, Cell, Tooltip, ResponsiveContainer, Legend } from 'recharts';
import { Wallet, Unlock, Heart } from 'lucide-react';

export default function WriterEarningsDashboard() {
  const { user } = useCurrentUser();
  const [data, setData] = useState(null);

  useEffect(() => {
    if (!user) return;
    let active = true;
    (async () => {
      try {
        const [purchases, tips] = await Promise.all([
          base44.entities.Purchase.filter({ writer_id: user.id, status: 'completed' }, '-created_date', 500),
          base44.entities.Tip.filter({ writer_id: user.id }, '-created_date', 500),
        ]);
        if (!active) return;
        const chapterTotal = purchases.reduce((s, p) => s + (p.writer_share || 0), 0);
        const tipTotal = tips.reduce((s, t) => s + (t.amount || 0), 0);
        setData({ chapterTotal, tipTotal, purchaseCount: purchases.length, tipCount: tips.length });
      } catch {
        if (active) setData({ chapterTotal: 0, tipTotal: 0, purchaseCount: 0, tipCount: 0 });
      }
    })();
    return () => { active = false; };
  }, [user]);

  if (!data) return <p className="text-sm text-muted-foreground">Loading earnings…</p>;

  const total = data.chapterTotal + data.tipTotal;
  const chartData = [
    { name: 'Chapter unlocks', value: +data.chapterTotal.toFixed(2), color: 'hsl(var(--chart-1))' },
    { name: 'Tips', value: +data.tipTotal.toFixed(2), color: 'hsl(var(--chart-4))' },
  ].filter((d) => d.value > 0);

  return (
    <div className="rounded-2xl border border-border/60 p-5 space-y-5">
      <div className="flex items-center gap-2">
        <Wallet className="w-4 h-4 text-muted-foreground" />
        <h2 className="font-heading text-xl font-semibold">Earnings dashboard</h2>
      </div>

      <div className="grid grid-cols-3 gap-3">
        <div className="rounded-xl bg-muted/40 p-4">
          <p className="text-xs text-muted-foreground">Total earnings</p>
          <p className="font-heading text-2xl font-semibold mt-1">${total.toFixed(2)}</p>
        </div>
        <div className="rounded-xl bg-muted/40 p-4">
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Unlock className="w-3.5 h-3.5" /> Chapter unlocks
          </div>
          <p className="font-heading text-2xl font-semibold mt-1">${data.chapterTotal.toFixed(2)}</p>
          <p className="text-xs text-muted-foreground mt-0.5">{data.purchaseCount} purchases</p>
        </div>
        <div className="rounded-xl bg-muted/40 p-4">
          <div className="flex items-center gap-1.5 text-xs text-muted-foreground">
            <Heart className="w-3.5 h-3.5" /> Tips
          </div>
          <p className="font-heading text-2xl font-semibold mt-1">${data.tipTotal.toFixed(2)}</p>
          <p className="text-xs text-muted-foreground mt-0.5">{data.tipCount} tips</p>
        </div>
      </div>

      {chartData.length === 0 ? (
        <p className="text-sm text-muted-foreground py-8 text-center">
          No earnings yet. As readers unlock chapters or send tips, your totals will appear here.
        </p>
      ) : (
        <ResponsiveContainer width="100%" height={240}>
          <PieChart>
            <Pie data={chartData} dataKey="value" nameKey="name" cx="50%" cy="50%" innerRadius={55} outerRadius={85} paddingAngle={2}>
              {chartData.map((d) => <Cell key={d.name} fill={d.color} />)}
            </Pie>
            <Tooltip formatter={(v) => `$${Number(v).toFixed(2)}`} contentStyle={{ background: 'hsl(var(--popover))', border: '1px solid hsl(var(--border))', borderRadius: 8, fontSize: 12 }} />
            <Legend wrapperStyle={{ fontSize: 12 }} />
          </PieChart>
        </ResponsiveContainer>
      )}
    </div>
  );
}
```

---

## `src/components/connect/ClientSetup.jsx`

```javascript
import { ExternalLink } from 'lucide-react';
import { Button } from '@/components/ui/button';

const APP_NAME = 'Chapterly';

function Step({ index, title, children }) {
  return (
    <li className="flex gap-3">
      <span className="mt-0.5 flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/15 text-xs font-semibold text-primary">
        {index}
      </span>
      <div className="min-w-0 space-y-2">
        <p className="text-sm font-medium leading-snug">{title}</p>
        {children && <p className="text-sm text-muted-foreground leading-relaxed">{children}</p>}
      </div>
    </li>
  );
}

function claudeLink(url) {
  const params = new URLSearchParams({
    modal: 'add-custom-connector',
    connectorName: APP_NAME,
    connectorUrl: url,
  });
  return `https://claude.ai/customize/connectors?${params.toString()}`;
}

// Ordered setup steps for one AI client.
export default function ClientSetup({ client, url }) {
  if (client === 'claude') {
    return (
      <ol className="space-y-4">
        <Step index={1} title="Open Claude's connector form">
          <Button asChild size="sm" className="mt-1">
            <a href={claudeLink(url)} target="_blank" rel="noreferrer">
              Add connector
              <ExternalLink className="w-3.5 h-3.5" />
            </a>
          </Button>
        </Step>
        <Step index={2} title="Confirm the server URL">
          It opens pre-filled. If the URL field is empty, paste the address from the top of this page.
        </Step>
        <Step index={3} title="Click Add">
          The connector appears in your list straight away.
        </Step>
      </ol>
    );
  }

  if (client === 'chatgpt') {
    return (
      <ol className="space-y-4">
        <Step index={1} title="Open ChatGPT and go to Settings, then Plugins">
          In the desktop app this lives behind your profile menu.
        </Step>
        <Step index={2} title="Open the MCPs tab and click Add server">
          On the web, custom servers are added through Developer mode instead.
        </Step>
        <Step index={3} title="Name it, then set Type to Streamable HTTP">
          Any name works — {APP_NAME} is a good one.
        </Step>
        <Step index={4} title="Paste the server URL and save">
          Use the address from the top of this page.
        </Step>
        <Step index={5} title="Restart ChatGPT and switch the server on">
          The tools appear in a conversation once it is enabled.
        </Step>
      </ol>
    );
  }

  if (client === 'cursor') {
    return (
      <ol className="space-y-4">
        <Step index={1} title="Open Customize, then the MCPs tab">
          Choose New MCP Server. Cursor opens your mcp.json file.
        </Step>
        <Step index={2} title="Add an entry that points at this address">
          <code className="mt-1 block overflow-x-auto rounded-lg bg-muted px-3 py-2 font-mono text-xs">
            {`{ "url": "${url}" }`}
          </code>
        </Step>
        <Step index={3} title="Save the file and toggle the server on">
          Cursor picks it up without a restart.
        </Step>
      </ol>
    );
  }

  return (
    <ol className="space-y-4">
      <Step index={1} title="Copy the server URL above">
        Every client that supports MCP accepts a streamable HTTP address.
      </Step>
      <Step index={2} title="Add it as a streamable HTTP MCP server">
        A name and the URL is usually all that is needed.
      </Step>
      <Step index={3} title="Reload the client">
        The connection is live once it reconnects.
      </Step>
    </ol>
  );
}
```

---

## `src/components/connect/CopyUrlField.jsx`

```javascript
import { useState } from 'react';
import { Check, Copy } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';

// Read-only server URL with a one-tap copy button. The URL is always resolved
// from the current origin, so it stays correct on the live domain and previews.
export default function CopyUrlField({ url }) {
  const [copied, setCopied] = useState(false);

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(url);
      setCopied(true);
      setTimeout(() => setCopied(false), 2000);
    } catch {
      setCopied(false);
    }
  };

  return (
    <div className="flex items-stretch gap-2">
      <Input
        readOnly
        value={url}
        aria-label="App server URL"
        className="h-11 font-mono text-xs sm:text-sm bg-muted/50"
        onFocus={(e) => e.target.select()}
      />
      <Button onClick={handleCopy} className="h-11 shrink-0" variant={copied ? 'secondary' : 'default'}>
        {copied ? <Check className="w-4 h-4" /> : <Copy className="w-4 h-4" />}
        <span className="hidden sm:inline">{copied ? 'Copied' : 'Copy'}</span>
      </Button>
    </div>
  );
}
```

---

## `src/components/cover/CoverCanvas.jsx`

```javascript
import { forwardRef } from 'react';

const CoverCanvas = forwardRef(function CoverCanvas({ config }, ref) {
  const bg = config.bgType === 'gradient'
    ? `linear-gradient(135deg, ${config.gradientFrom || '#1e3a8a'}, ${config.gradientTo || '#0ea5e9'})`
    : config.bgType === 'image' && config.imageUrl
      ? `url(${config.imageUrl}) center/cover no-repeat`
      : (config.bgColor || '#1e3a8a');

  const alignItems = config.titlePosition === 'top' ? 'flex-start' : config.titlePosition === 'bottom' ? 'flex-end' : 'center';

  return (
    <div
      ref={ref}
      style={{
        width: 320,
        height: 480,
        background: bg,
        borderRadius: 12,
        position: 'relative',
        overflow: 'hidden',
        boxShadow: '0 12px 32px rgba(0,0,0,0.25)',
      }}
    >
      {config.bgType === 'image' && config.imageUrl && (
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(0,0,0,0.15), rgba(0,0,0,0.45))' }} />
      )}
      <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', padding: '24px 20px' }}>
        <div style={{ flex: 1, display: 'flex', alignItems, justifyContent: 'center' }}>
          <h1
            style={{
              color: config.titleColor || '#ffffff',
              fontFamily: config.titleFont || 'serif',
              fontSize: config.titleSize || 34,
              textAlign: config.titleAlign || 'center',
              lineHeight: 1.1,
              margin: 0,
              textShadow: '0 2px 10px rgba(0,0,0,0.55)',
            }}
          >
            {config.title || 'Your Story Title'}
          </h1>
        </div>
        <div
          style={{
            textAlign: config.titleAlign || 'center',
            color: config.authorColor || '#e2e8f0',
            fontFamily: config.titleFont || 'serif',
            fontSize: config.authorSize || 16,
            letterSpacing: 1,
            textShadow: '0 1px 6px rgba(0,0,0,0.5)',
          }}
        >
          {config.author || 'Author Name'}
        </div>
      </div>
    </div>
  );
});

export default CoverCanvas;
```

---

## `src/components/cover/CoverControls.jsx`

```javascript
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Loader2, Sparkles, Upload } from 'lucide-react';
import DrawerSelect from '@/components/DrawerSelect';

const GRADIENTS = [
  { from: '#1e3a8a', to: '#0ea5e9' },
  { from: '#7c2d12', to: '#f59e0b' },
  { from: '#831843', to: '#ec4899' },
  { from: '#064e3b', to: '#10b981' },
  { from: '#1f2937', to: '#6b7280' },
  { from: '#4c1d95', to: '#a78bfa' },
];

const FONTS = [
  { label: 'Serif', value: 'Georgia, serif' },
  { label: 'Sans', value: 'Inter, system-ui, sans-serif' },
  { label: 'Display', value: 'Impact, sans-serif' },
  { label: 'Mono', value: 'Courier New, monospace' },
];

const LAYOUTS = [
  { label: 'Top', value: 'top' },
  { label: 'Center', value: 'center' },
  { label: 'Bottom', value: 'bottom' },
];

export default function CoverControls({ config, setConfig, onGenerate, onUpload, generating }) {
  const set = (patch) => setConfig((c) => ({ ...c, ...patch }));

  return (
    <div className="space-y-5">
      <div>
        <Label className="text-xs uppercase tracking-wide text-muted-foreground">Background</Label>
        <div className="flex gap-2 mt-2">
          {['color', 'gradient', 'image'].map((t) => (
            <Button
              key={t}
              size="sm"
              variant={config.bgType === t ? 'default' : 'outline'}
              className="rounded-full capitalize"
              onClick={() => set({ bgType: t })}
            >
              {t}
            </Button>
          ))}
        </div>

        {config.bgType === 'color' && (
          <div className="flex items-center gap-2 mt-3">
            <input type="color" value={config.bgColor} onChange={(e) => set({ bgColor: e.target.value })} className="w-9 h-9 rounded border border-input cursor-pointer" />
            <Input value={config.bgColor} onChange={(e) => set({ bgColor: e.target.value })} className="max-w-[120px]" />
          </div>
        )}

        {config.bgType === 'gradient' && (
          <div className="grid grid-cols-6 gap-2 mt-3">
            {GRADIENTS.map((g, i) => (
              <button
                key={i}
                type="button"
                onClick={() => set({ gradientFrom: g.from, gradientTo: g.to })}
                className="h-9 rounded-md border border-border"
                style={{ background: `linear-gradient(135deg, ${g.from}, ${g.to})` }}
                aria-label={`Gradient ${i + 1}`}
              />
            ))}
          </div>
        )}

        {config.bgType === 'image' && (
          <div className="space-y-2 mt-3">
            <div className="flex gap-2">
              <Input placeholder="Describe cover art (e.g. misty forest, dragon over castle)" value={config.aiPrompt || ''} onChange={(e) => set({ aiPrompt: e.target.value })} />
              <Button size="sm" onClick={onGenerate} disabled={generating} className="rounded-full shrink-0">
                {generating ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4" />}
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">Or upload your own art:</p>
            <label className="inline-flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-full border border-input cursor-pointer hover:bg-accent">
              <Upload className="w-4 h-4" /> Upload image
              <input type="file" accept="image/*" className="hidden" onChange={onUpload} />
            </label>
          </div>
        )}
      </div>

      <div className="space-y-2">
        <Label htmlFor="cv-title">Title</Label>
        <Input id="cv-title" value={config.title} onChange={(e) => set({ title: e.target.value })} />
      </div>

      <div className="space-y-2">
        <Label htmlFor="cv-author">Author</Label>
        <Input id="cv-author" value={config.author} onChange={(e) => set({ author: e.target.value })} />
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-2">
          <Label>Font</Label>
          <DrawerSelect
            label="Title font"
            value={config.titleFont}
            options={FONTS}
            onChange={(v) => set({ titleFont: v })}
          />
        </div>
        <div className="space-y-2">
          <Label>Layout</Label>
          <DrawerSelect
            label="Layout"
            value={config.titlePosition}
            options={LAYOUTS}
            onChange={(v) => set({ titlePosition: v })}
          />
        </div>
      </div>

      <div className="grid grid-cols-2 gap-3">
        <div className="space-y-2">
          <Label>Title size</Label>
          <input type="range" min={20} max={52} value={config.titleSize} onChange={(e) => set({ titleSize: Number(e.target.value) })} className="w-full" />
        </div>
        <div className="space-y-2">
          <Label>Align</Label>
          <div className="flex gap-1">
            {['left', 'center', 'right'].map((a) => (
              <Button key={a} size="sm" variant={config.titleAlign === a ? 'default' : 'outline'} className="rounded-full flex-1" onClick={() => set({ titleAlign: a })}>
                {a[0].toUpperCase()}
              </Button>
            ))}
          </div>
        </div>
      </div>

      <div className="flex items-center gap-4">
        <div className="flex items-center gap-2">
          <Label className="text-xs">Title</Label>
          <input type="color" value={config.titleColor} onChange={(e) => set({ titleColor: e.target.value })} className="w-8 h-8 rounded border border-input cursor-pointer" />
        </div>
        <div className="flex items-center gap-2">
          <Label className="text-xs">Author</Label>
          <input type="color" value={config.authorColor} onChange={(e) => set({ authorColor: e.target.value })} className="w-8 h-8 rounded border border-input cursor-pointer" />
        </div>
      </div>
    </div>
  );
}
```

---

## `src/components/cover/TemplateGallery.jsx`

```javascript
import { Image } from '@/components/ui/image';
import { Button } from '@/components/ui/button';
import { Loader2, Check, Lock } from 'lucide-react';

export default function TemplateGallery({ templates, onApply, onBuy, buyingId }) {
  if (!templates.length) {
    return <p className="text-sm text-muted-foreground">No templates yet. Save your design as a template to share it.</p>;
  }
  return (
    <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
      {templates.map((t) => (
        <div key={t.id} className="rounded-xl border border-border/60 bg-card overflow-hidden flex flex-col">
          <div className="aspect-[2/3] bg-muted">
            {t.cover_url && <Image src={t.cover_url} fittingType="fill" className="w-full h-full" alt={t.title} />}
          </div>
          <div className="p-2 flex flex-col gap-1.5 flex-1">
            <p className="text-xs font-medium line-clamp-1">{t.title}</p>
            <p className="text-[10px] text-muted-foreground">{t.is_free ? 'Free' : `$${Number(t.price).toFixed(2)}`} · {t.usage_count || 0} uses</p>
            {t.is_free ? (
              <Button size="sm" variant="outline" className="rounded-full w-full" onClick={() => onApply(t)}>
                <Check className="w-3.5 h-3.5" /> Use
              </Button>
            ) : (
              <Button size="sm" className="rounded-full w-full" disabled={buyingId === t.id} onClick={() => onBuy(t)}>
                {buyingId === t.id ? <Loader2 className="w-3.5 h-3.5 animate-spin" /> : <Lock className="w-3.5 h-3.5" />}
                {buyingId === t.id ? 'Redirecting' : 'Get'}
              </Button>
            )}
          </div>
        </div>
      ))}
    </div>
  );
}
```

---

## `src/components/genre/GenreDialog.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import DrawerSelect from '@/components/DrawerSelect';
import { useToast } from '@/components/ui/use-toast';
import { createGenre, loadGenres, topLevelNames } from '@/lib/genres';

/**
 * Lets any signed-in reader or writer add a new genre, or a sub-category
 * inside an existing genre.
 */
export default function GenreDialog({ open, onOpenChange, defaultParentName = '', onCreated }) {
  const { toast } = useToast();
  const [genres, setGenres] = useState([]);
  const [name, setName] = useState('');
  const [parent, setParent] = useState(defaultParentName);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!open) return;
    setParent(defaultParentName);
    loadGenres().then(setGenres).catch(() => {});
  }, [open, defaultParentName]);

  const parentOptions = [
    { value: '', label: 'Top-level genre' },
    ...topLevelNames(genres).map((g) => ({ value: g, label: `Sub-category of ${g}` })),
  ];

  const submit = async () => {
    if (!name.trim()) return;
    setSaving(true);
    try {
      const parentId = parent
        ? genres.find((g) => !g.parent_id && g.name === parent)?.id || ''
        : '';
      const created = await createGenre({ name, parentId });
      toast({
        title: parent ? `Sub-category added to ${parent}` : 'Genre added',
        description: created.name,
      });
      setName('');
      onOpenChange(false);
      onCreated?.(created);
    } catch (e) {
      toast({ title: 'Could not add that category', description: String(e?.message || e), variant: 'destructive' });
    }
    setSaving(false);
  };

  return (
    <Dialog open={open} onOpenChange={onOpenChange}>
      <DialogContent className="sm:max-w-md">
        <DialogHeader>
          <DialogTitle>Add a genre or sub-category</DialogTitle>
          <DialogDescription>
            New categories appear for everyone browsing Chapterly.
          </DialogDescription>
        </DialogHeader>

        <div className="space-y-4">
          <div>
            <Label htmlFor="genre-name">Name</Label>
            <Input
              id="genre-name"
              value={name}
              onChange={(e) => setName(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), submit())}
              placeholder="e.g. Fanfiction"
              className="mt-1.5"
            />
          </div>
          <div>
            <Label>Where it belongs</Label>
            <div className="mt-1.5">
              <DrawerSelect label="Where it belongs" value={parent} options={parentOptions} onChange={setParent} />
            </div>
          </div>
        </div>

        <DialogFooter>
          <Button variant="outline" onClick={() => onOpenChange(false)}>Cancel</Button>
          <Button onClick={submit} disabled={saving || !name.trim()}>
            {saving ? 'Adding…' : 'Add category'}
          </Button>
        </DialogFooter>
      </DialogContent>
    </Dialog>
  );
}
```

---

## `src/components/genre/GenrePicker.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Plus } from 'lucide-react';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
import { createGenre, genreIdFor, loadGenres, subGenreNames, topLevelNames } from '@/lib/genres';

const chip = (active) =>
  `px-3 py-1 rounded-full text-xs transition ${
    active
      ? 'bg-foreground text-background'
      : 'border border-border text-muted-foreground hover:text-foreground hover:bg-muted'
  }`;

/** Genre + optional sub-category picker for the story editor, with inline creation. */
export default function GenrePicker({ genre, subGenre, onChange }) {
  const { toast } = useToast();
  const [genres, setGenres] = useState([]);
  const [adding, setAdding] = useState(null); // 'genre' | 'sub'
  const [draft, setDraft] = useState('');
  const [saving, setSaving] = useState(false);

  const reload = () => loadGenres().then(setGenres).catch(() => {});
  useEffect(() => { reload(); }, []);

  const tops = topLevelNames(genres);
  const subs = subGenreNames(genres, genre);

  const commit = async (kind) => {
    if (!draft.trim()) return;
    setSaving(true);
    try {
      if (kind === 'sub') {
        const parentId = genreIdFor(genres, genre);
        if (!parentId) throw new Error('Pick a genre first');
        const created = await createGenre({ name: draft, parentId });
        await reload();
        onChange({ genre, subGenre: created.name });
      } else {
        const created = await createGenre({ name: draft });
        await reload();
        onChange({ genre: created.name, subGenre: '' });
      }
      setDraft('');
      setAdding(null);
    } catch (e) {
      toast({ title: 'Could not add that category', description: String(e?.message || e), variant: 'destructive' });
    }
    setSaving(false);
  };

  return (
    <div className="space-y-3">
      <div>
        <Label>Genre</Label>
        <div className="flex flex-wrap gap-1.5 mt-1.5">
          {tops.map((g) => (
            <button
              type="button"
              key={g}
              onClick={() => onChange({ genre: g, subGenre: '' })}
              className={chip(genre === g)}
            >
              {g}
            </button>
          ))}
          <button
            type="button"
            onClick={() => { setAdding(adding === 'genre' ? null : 'genre'); setDraft(''); }}
            className="px-3 py-1 rounded-full text-xs border border-dashed border-border text-muted-foreground hover:text-foreground hover:bg-muted inline-flex items-center gap-1"
          >
            <Plus className="w-3 h-3" /> New genre
          </button>
        </div>
        {adding === 'genre' && (
          <div className="flex gap-2 mt-2">
            <Input
              value={draft}
              autoFocus
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), commit('genre'))}
              placeholder="Name your new genre"
            />
            <Button type="button" variant="outline" disabled={saving || !draft.trim()} onClick={() => commit('genre')}>
              Add
            </Button>
          </div>
        )}
      </div>

      <div>
        <Label>Sub-category (optional)</Label>
        <div className="flex flex-wrap gap-1.5 mt-1.5">
          <button type="button" onClick={() => onChange({ genre, subGenre: '' })} className={chip(!subGenre)}>
            None
          </button>
          {subs.map((s) => (
            <button
              type="button"
              key={s}
              onClick={() => onChange({ genre, subGenre: subGenre === s ? '' : s })}
              className={chip(subGenre === s)}
            >
              {s}
            </button>
          ))}
          <button
            type="button"
            onClick={() => { setAdding(adding === 'sub' ? null : 'sub'); setDraft(''); }}
            className="px-3 py-1 rounded-full text-xs border border-dashed border-border text-muted-foreground hover:text-foreground hover:bg-muted inline-flex items-center gap-1"
          >
            <Plus className="w-3 h-3" /> New sub-category
          </button>
        </div>
        {adding === 'sub' && (
          <div className="flex gap-2 mt-2">
            <Input
              value={draft}
              autoFocus
              onChange={(e) => setDraft(e.target.value)}
              onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), commit('sub'))}
              placeholder={`Inside ${genre || 'a genre'}`}
            />
            <Button type="button" variant="outline" disabled={saving || !draft.trim()} onClick={() => commit('sub')}>
              Add
            </Button>
          </div>
        )}
      </div>
    </div>
  );
}
```

---

## `src/components/marketing/CombinedTrendChart.jsx`

```javascript
import { LineChart, Line, XAxis, YAxis, Tooltip, ResponsiveContainer, CartesianGrid, Legend, ReferenceLine } from 'recharts';

const fmtWeek = (w) => new Date(w).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });

export default function CombinedTrendChart({ kpis }) {
  const [reads, signups, paid] = kpis;
  if (!reads || !signups || !paid) return null;

  const len = Math.max(reads.series?.length || 0, signups.series?.length || 0, paid.series?.length || 0);
  const pct = (v, t) => Math.round(((v || 0) / (t || 1)) * 100);

  const data = [];
  for (let i = 0; i < len; i++) {
    const r = reads.series[i], s = signups.series[i], p = paid.series[i];
    data.push({
      week: (r || s || p).week,
      Reads: r ? pct(r.value, reads.target) : 0,
      Signups: s ? pct(s.value, signups.target) : 0,
      Paid: p ? pct(p.value, paid.target) : 0,
    });
  }

  return (
    <div className="rounded-2xl border border-border/60 bg-card p-5">
      <div className="flex items-center justify-between mb-4">
        <h3 className="text-sm font-medium">All trends — % of weekly target</h3>
        <span className="text-xs text-muted-foreground">100% = on target</span>
      </div>
      <div className="h-64">
        <ResponsiveContainer width="100%" height="100%">
          <LineChart data={data} margin={{ top: 5, right: 10, left: -20, bottom: 0 }}>
            <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
            <XAxis dataKey="week" tickFormatter={fmtWeek} tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
            <YAxis tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" domain={[0, 'auto']} allowDecimals={false} />
            <Tooltip labelFormatter={fmtWeek} contentStyle={{ borderRadius: 12, border: '1px solid hsl(var(--border))', fontSize: 12, background: 'hsl(var(--popover))' }} formatter={(v) => `${v}%`} />
            <Legend wrapperStyle={{ fontSize: 12 }} />
            <ReferenceLine y={100} stroke="hsl(var(--secondary))" strokeDasharray="4 4" />
            <Line type="monotone" dataKey="Reads" stroke="hsl(var(--chart-1))" strokeWidth={2} dot={false} />
            <Line type="monotone" dataKey="Signups" stroke="hsl(var(--chart-2))" strokeWidth={2} dot={false} />
            <Line type="monotone" dataKey="Paid" stroke="hsl(var(--chart-3))" strokeWidth={2} dot={false} />
          </LineChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
```

---

## `src/components/marketing/KpiCard.jsx`

```javascript
import { ArrowUpRight, ArrowDownRight, Target } from 'lucide-react';
import { cn } from '@/lib/utils';

export default function KpiCard({ label, current, target, change, icon: Icon }) {
  const up = change >= 0;
  return (
    <div className="rounded-2xl border border-border/60 bg-card p-5 space-y-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-sm text-muted-foreground">
          {Icon && <Icon className="w-4 h-4" />}
          {label}
        </div>
        <span className={cn(
          'inline-flex items-center gap-0.5 text-xs font-medium px-2 py-0.5 rounded-full',
          up ? 'bg-accent text-accent-foreground' : 'bg-destructive/10 text-destructive'
        )}>
          {up ? <ArrowUpRight className="w-3 h-3" /> : <ArrowDownRight className="w-3 h-3" />}
          {Math.abs(change)}%
        </span>
      </div>
      <div className="flex items-end justify-between">
        <div>
          <p className="text-3xl font-semibold tracking-tight">{(current || 0).toLocaleString()}</p>
          <p className="text-xs text-muted-foreground mt-1">this week</p>
        </div>
        <div className="text-right">
          <p className="text-xs text-muted-foreground inline-flex items-center gap-1"><Target className="w-3 h-3" /> target</p>
          <p className="text-sm font-medium">{target.toLocaleString()}/wk</p>
        </div>
      </div>
    </div>
  );
}
```

---

## `src/components/marketing/KpiTrendChart.jsx`

```javascript
import { AreaChart, Area, XAxis, YAxis, Tooltip, ResponsiveContainer, ReferenceLine, CartesianGrid } from 'recharts';

const fmtWeek = (w) => {
  const d = new Date(w);
  return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
};

export default function KpiTrendChart({ label, series, target, color = 'hsl(var(--chart-1))' }) {
  const gid = 'g-' + label.replace(/[^a-z0-9]/gi, '');
  return (
    <div className="rounded-2xl border border-border/60 bg-card p-5">
      <h3 className="text-sm font-medium mb-4">{label} — weekly trend</h3>
      <div className="h-48">
        <ResponsiveContainer width="100%" height="100%">
          <AreaChart data={series} margin={{ top: 5, right: 5, left: -20, bottom: 0 }}>
            <defs>
              <linearGradient id={gid} x1="0" y1="0" x2="0" y2="1">
                <stop offset="5%" stopColor={color} stopOpacity={0.3} />
                <stop offset="95%" stopColor={color} stopOpacity={0} />
              </linearGradient>
            </defs>
            <CartesianGrid strokeDasharray="3 3" stroke="hsl(var(--border))" vertical={false} />
            <XAxis dataKey="week" tickFormatter={fmtWeek} tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" />
            <YAxis tick={{ fontSize: 11 }} stroke="hsl(var(--muted-foreground))" allowDecimals={false} />
            <Tooltip labelFormatter={fmtWeek} contentStyle={{ borderRadius: 12, border: '1px solid hsl(var(--border))', fontSize: 12, background: 'hsl(var(--popover))' }} />
            <ReferenceLine y={target} stroke="hsl(var(--secondary))" strokeDasharray="4 4" label={{ value: 'target', fontSize: 10, fill: 'hsl(var(--muted-foreground))', position: 'insideTopRight' }} />
            <Area type="monotone" dataKey="value" stroke={color} strokeWidth={2} fill={`url(#${gid})`} />
          </AreaChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
}
```

---

## `src/components/reviews/StarPicker.jsx`

```javascript
import { useState } from 'react';
import { Star } from 'lucide-react';

export default function StarPicker({ value = 0, onChange, disabled = false, readOnly = false, size = 'md' }) {
  const [hover, setHover] = useState(0);
  const display = hover || value;
  const dims = size === 'sm' ? 'w-3.5 h-3.5' : 'w-5 h-5';

  return (
    <div className="flex items-center gap-0.5" onMouseLeave={() => setHover(0)}>
      {[1, 2, 3, 4, 5].map((n) => (
        <button
          key={n}
          type="button"
          disabled={disabled || readOnly}
          onMouseEnter={() => !disabled && !readOnly && setHover(n)}
          onClick={() => onChange?.(n)}
          className="p-0.5 disabled:cursor-default"
          aria-label={`${n} star${n > 1 ? 's' : ''}`}
        >
          <Star
            className={`${dims} transition-colors ${
              n <= display ? 'fill-amber-400 text-amber-400' : 'text-muted-foreground/40'
            }`}
          />
        </button>
      ))}
    </div>
  );
}
```

---

## `src/components/reviews/StoryRatingsOverview.jsx`

```javascript
import { useEffect, useMemo, useState } from 'react';
import moment from 'moment';
import StarPicker from '@/components/reviews/StarPicker';
import { getPublicProfiles } from '@/lib/publicProfiles';
import { Star } from 'lucide-react';

function reviewerName(profile) {
  return profile?.display_name || profile?.full_name || 'A reader';
}

export default function StoryRatingsOverview({ stories = [], ratings = [] }) {
  const [names, setNames] = useState({});

  useEffect(() => {
    let active = true;
    (async () => {
      const map = await getPublicProfiles(ratings.map((r) => r.user_id)).catch(() => ({}));
      if (active) setNames(map);
    })();
    return () => { active = false; };
  }, [ratings]);

  const count = ratings.length;
  const avg = count ? ratings.reduce((sum, r) => sum + (r.value || 0), 0) / count : 0;

  const perStory = useMemo(() => {
    return stories
      .map((story) => {
        const rs = ratings.filter((r) => r.story_id === story.id);
        return {
          story,
          count: rs.length,
          avg: rs.length ? rs.reduce((sum, r) => sum + (r.value || 0), 0) / rs.length : 0,
        };
      })
      .filter((x) => x.count > 0)
      .sort((a, b) => b.count - a.count);
  }, [stories, ratings]);

  const recent = useMemo(
    () =>
      ratings
        .filter((r) => (r.review || '').trim())
        .sort((a, b) => new Date(b.created_date || 0) - new Date(a.created_date || 0))
        .slice(0, 5),
    [ratings]
  );

  const titleFor = (storyId) => stories.find((s) => s.id === storyId)?.title || 'Your story';

  return (
    <section className="rounded-2xl border border-border/60 bg-card p-5 sm:p-6">
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <h2 className="font-heading text-xl font-semibold">Ratings &amp; reviews</h2>
          <p className="text-sm text-muted-foreground mt-0.5">How readers are responding to your stories.</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="text-right">
            <p className="font-heading text-2xl font-semibold leading-none">{count ? avg.toFixed(1) : '—'}</p>
            <p className="text-xs text-muted-foreground mt-1">{count} {count === 1 ? 'rating' : 'ratings'}</p>
          </div>
          <StarPicker value={Math.round(avg)} readOnly size="sm" />
        </div>
      </div>

      {count === 0 ? (
        <p className="mt-5 text-sm text-muted-foreground">
          No ratings yet. Once readers rate your stories, their feedback shows up here.
        </p>
      ) : (
        <>
          {perStory.length > 0 && (
            <div className="mt-5 space-y-2">
              {perStory.map(({ story, count: c, avg: a }) => (
                <div key={story.id} className="flex items-center justify-between gap-3 rounded-xl bg-muted/30 px-3 py-2">
                  <span className="text-sm font-medium truncate">{story.title}</span>
                  <span className="flex items-center gap-2 shrink-0 text-sm text-muted-foreground">
                    <Star className="w-3.5 h-3.5 fill-amber-400 text-amber-400" />
                    <span className="font-medium text-foreground">{a.toFixed(1)}</span>
                    <span className="text-xs">({c})</span>
                  </span>
                </div>
              ))}
            </div>
          )}

          {recent.length > 0 && (
            <div className="mt-5">
              <h3 className="text-xs uppercase tracking-wide text-muted-foreground mb-3">Recent reviews</h3>
              <ul className="divide-y divide-border">
                {recent.map((r) => (
                  <li key={r.id} className="py-3 first:pt-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-sm font-medium">{reviewerName(names[r.user_id])}</span>
                      <StarPicker value={r.value} readOnly size="sm" />
                      <span className="text-xs text-muted-foreground">
                        {r.created_date ? moment(r.created_date).fromNow() : ''}
                      </span>
                      <span className="text-xs text-muted-foreground">· {titleFor(r.story_id)}</span>
                    </div>
                    <p className="text-sm text-foreground/80 leading-relaxed mt-1 whitespace-pre-wrap">{r.review}</p>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </>
      )}
    </section>
  );
}
```

---

## `src/components/reviews/StoryReviews.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import StarPicker from '@/components/reviews/StarPicker';
import { getPublicProfiles } from '@/lib/publicProfiles';
import moment from 'moment';
import { Star, Trash2 } from 'lucide-react';

function reviewerName(profile) {
  return profile?.display_name || profile?.full_name || 'A reader';
}

export default function StoryReviews({ storyId, storyOwnerId }) {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [ratings, setRatings] = useState([]);
  const [names, setNames] = useState({});
  const [value, setValue] = useState(0);
  const [review, setReview] = useState('');
  const [writing, setWriting] = useState(false);
  const [saving, setSaving] = useState(false);

  const isAuthor = Boolean(user && storyOwnerId && user.id === storyOwnerId);
  const mine = user ? ratings.find((r) => r.user_id === user.id) : null;

  useEffect(() => {
    let active = true;
    (async () => {
      const all = await base44.entities.Rating.filter({ story_id: storyId }, '-created_date').catch(() => []);
      if (!active) return;
      setRatings(all);
      const map = await getPublicProfiles(all.map((r) => r.user_id)).catch(() => ({}));
      if (active) setNames(map);
    })();
    return () => { active = false; };
  }, [storyId]);

  useEffect(() => {
    if (!mine) return;
    setValue(mine.value || 0);
    setReview(mine.review || '');
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mine?.id]);

  const count = ratings.length;
  const avg = count ? ratings.reduce((sum, r) => sum + (r.value || 0), 0) / count : 0;
  const distribution = [5, 4, 3, 2, 1].map((n) => ({ n, c: ratings.filter((r) => r.value === n).length }));
  const written = ratings
    .filter((r) => (r.review || '').trim())
    .sort((a, b) => new Date(b.created_date || 0) - new Date(a.created_date || 0));

  const submit = async () => {
    if (!user) return toast({ title: 'Sign in to review this story' });
    if (!value) return toast({ title: 'Pick a star rating first' });
    if (saving) return;
    setSaving(true);
    try {
      const payload = { value, review: review.trim() };
      if (mine) {
        await base44.entities.Rating.update(mine.id, payload);
        setRatings((prev) => prev.map((r) => (r.id === mine.id ? { ...r, ...payload } : r)));
      } else {
        const created = await base44.entities.Rating.create({ user_id: user.id, story_id: storyId, ...payload });
        setRatings((prev) => [created, ...prev]);
      }
      setWriting(false);
      toast({ title: 'Thanks for sharing your thoughts' });
    } catch (e) {
      toast({ title: 'Could not save your review', description: e.message, variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  const removeMine = async () => {
    if (!mine) return;
    try {
      await base44.entities.Rating.delete(mine.id);
      setRatings((prev) => prev.filter((r) => r.id !== mine.id));
      setValue(0);
      setReview('');
      setWriting(false);
      toast({ title: 'Your rating was removed' });
    } catch (e) {
      toast({ title: 'Could not remove your review', description: e.message, variant: 'destructive' });
    }
  };

  return (
    <section className="rounded-2xl border border-border/60 bg-card p-5 sm:p-6">
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <h2 className="font-heading text-xl font-semibold">Reader reviews</h2>
          <p className="text-sm text-muted-foreground mt-0.5">What readers thought of this story.</p>
        </div>
        <div className="flex items-center gap-3">
          <div className="text-right">
            <p className="font-heading text-2xl font-semibold leading-none">{count ? avg.toFixed(1) : '—'}</p>
            <p className="text-xs text-muted-foreground mt-1">{count} {count === 1 ? 'rating' : 'ratings'}</p>
          </div>
          <StarPicker value={Math.round(avg)} readOnly size="sm" />
        </div>
      </div>

      {count > 0 && (
        <div className="mt-5 grid sm:grid-cols-2 gap-6">
          <div className="space-y-1.5">
            {distribution.map(({ n, c }) => (
              <div key={n} className="flex items-center gap-2 text-xs text-muted-foreground">
                <span className="w-8 shrink-0">{n}<Star className="inline w-3 h-3 ml-0.5 fill-amber-400 text-amber-400" /></span>
                <div className="flex-1 h-1.5 rounded-full bg-muted overflow-hidden">
                  <div className="h-full bg-amber-400" style={{ width: `${count ? (c / count) * 100 : 0}%` }} />
                </div>
                <span className="w-6 text-right">{c}</span>
              </div>
            ))}
          </div>

          <div className="sm:text-right">
            {!isAuthor && (
              <>
                {!writing && (
                  <Button variant="outline" className="rounded-full" onClick={() => setWriting(true)}>
                    {mine ? 'Edit your review' : 'Write a review'}
                  </Button>
                )}
              </>
            )}
            {isAuthor && (
              <p className="text-xs text-muted-foreground">
                This is your story — {written.length ? 'reader feedback is below.' : 'reader feedback will appear here.'}
              </p>
            )}
          </div>
        </div>
      )}

      {!isAuthor && !writing && count === 0 && (
        <div className="mt-5">
          <Button variant="outline" className="rounded-full" onClick={() => setWriting(true)}>
            Write a review
          </Button>
        </div>
      )}

      {!isAuthor && writing && (
        <div className="mt-5 rounded-xl border border-border/60 bg-muted/30 p-4">
          <p className="text-sm font-medium mb-2">Your rating</p>
          <StarPicker value={value} onChange={setValue} disabled={saving} />
          <p className="text-sm font-medium mt-4 mb-2">Your review</p>
          <Textarea
            value={review}
            onChange={(e) => setReview(e.target.value)}
            placeholder="Did the characters stay with you? Did the pacing work? Share what you felt."
            rows={4}
            disabled={saving}
          />
          <div className="mt-3 flex items-center gap-2">
            <Button className="rounded-full" onClick={submit} disabled={saving}>
              {saving ? 'Saving…' : mine ? 'Update review' : 'Post review'}
            </Button>
            <Button variant="ghost" className="rounded-full" onClick={() => setWriting(false)} disabled={saving}>
              Cancel
            </Button>
            {mine && (
              <Button variant="ghost" className="rounded-full text-destructive ml-auto" onClick={removeMine} disabled={saving}>
                <Trash2 className="w-4 h-4 mr-1.5" /> Remove
              </Button>
            )}
          </div>
        </div>
      )}

      {written.length === 0 ? (
        <p className="mt-5 text-sm text-muted-foreground">No written reviews yet. Be the first to share your thoughts.</p>
      ) : (
        <ul className="mt-5 divide-y divide-border">
          {written.map((r) => {
            const profile = names[r.user_id];
            const name = reviewerName(profile);
            const isMine = user && r.user_id === user.id;
            return (
              <li key={r.id} className="py-4 first:pt-0">
                <div className="flex items-start gap-3">
                  <div className="w-8 h-8 rounded-full bg-muted flex items-center justify-center shrink-0 text-xs font-medium">
                    {name.charAt(0).toUpperCase()}
                  </div>
                  <div className="min-w-0 flex-1">
                    <div className="flex items-center gap-2 flex-wrap">
                      <span className="text-sm font-medium">{isMine ? 'You' : name}</span>
                      <StarPicker value={r.value} readOnly size="sm" />
                      <span className="text-xs text-muted-foreground">
                        {r.created_date ? moment(r.created_date).fromNow() : ''}
                      </span>
                      {isMine && (
                        <button
                          type="button"
                          onClick={removeMine}
                          className="text-xs text-muted-foreground hover:text-destructive ml-auto"
                        >
                          Remove
                        </button>
                      )}
                    </div>
                    <p className="text-sm text-foreground/80 leading-relaxed mt-1.5 whitespace-pre-wrap">{r.review}</p>
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      )}
    </section>
  );
}
```

---

## `src/components/ui/accordion.jsx`

```javascript
import * as React from "react"
import * as AccordionPrimitive from "@radix-ui/react-accordion"
import { ChevronDown } from "lucide-react"

import { cn } from "@/lib/utils"

const Accordion = AccordionPrimitive.Root

const AccordionItem = React.forwardRef(({ className, ...props }, ref) => (
  <AccordionPrimitive.Item ref={ref} className={cn("border-b", className)} {...props} />
))
AccordionItem.displayName = "AccordionItem"

const AccordionTrigger = React.forwardRef(({ className, children, ...props }, ref) => (
  <AccordionPrimitive.Header className="flex">
    <AccordionPrimitive.Trigger
      ref={ref}
      className={cn(
        "flex flex-1 items-center justify-between py-4 text-sm font-medium transition-all hover:underline text-left [&[data-state=open]>svg]:rotate-180",
        className
      )}
      {...props}>
      {children}
      <ChevronDown
        className="h-4 w-4 shrink-0 text-muted-foreground transition-transform duration-200" />
    </AccordionPrimitive.Trigger>
  </AccordionPrimitive.Header>
))
AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName

const AccordionContent = React.forwardRef(({ className, children, ...props }, ref) => (
  <AccordionPrimitive.Content
    ref={ref}
    className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
    {...props}>
    <div className={cn("pb-4 pt-0", className)}>{children}</div>
  </AccordionPrimitive.Content>
))
AccordionContent.displayName = AccordionPrimitive.Content.displayName

export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }

```

---

## `src/components/ui/alert-dialog.jsx`

```javascript
import * as React from "react"
import * as AlertDialogPrimitive from "@radix-ui/react-alert-dialog"

import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"

const AlertDialog = AlertDialogPrimitive.Root

const AlertDialogTrigger = AlertDialogPrimitive.Trigger

const AlertDialogPortal = AlertDialogPrimitive.Portal

const AlertDialogOverlay = React.forwardRef(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Overlay
    className={cn(
      "fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
      className
    )}
    {...props}
    ref={ref} />
))
AlertDialogOverlay.displayName = AlertDialogPrimitive.Overlay.displayName

const AlertDialogContent = React.forwardRef(({ className, ...props }, ref) => (
  <AlertDialogPortal>
    <AlertDialogOverlay />
    <AlertDialogPrimitive.Content
      ref={ref}
      className={cn(
        "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
        className
      )}
      {...props} />
  </AlertDialogPortal>
))
AlertDialogContent.displayName = AlertDialogPrimitive.Content.displayName

const AlertDialogHeader = ({
  className,
  ...props
}) => (
  <div
    className={cn("flex flex-col space-y-2 text-center sm:text-left", className)}
    {...props} />
)
AlertDialogHeader.displayName = "AlertDialogHeader"

const AlertDialogFooter = ({
  className,
  ...props
}) => (
  <div
    className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
    {...props} />
)
AlertDialogFooter.displayName = "AlertDialogFooter"

const AlertDialogTitle = React.forwardRef(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Title ref={ref} className={cn("text-lg font-semibold", className)} {...props} />
))
AlertDialogTitle.displayName = AlertDialogPrimitive.Title.displayName

const AlertDialogDescription = React.forwardRef(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Description
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    {...props} />
))
AlertDialogDescription.displayName =
  AlertDialogPrimitive.Description.displayName

const AlertDialogAction = React.forwardRef(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Action ref={ref} className={cn(buttonVariants(), className)} {...props} />
))
AlertDialogAction.displayName = AlertDialogPrimitive.Action.displayName

const AlertDialogCancel = React.forwardRef(({ className, ...props }, ref) => (
  <AlertDialogPrimitive.Cancel
    ref={ref}
    className={cn(buttonVariants({ variant: "outline" }), "mt-2 sm:mt-0", className)}
    {...props} />
))
AlertDialogCancel.displayName = AlertDialogPrimitive.Cancel.displayName

export {
  AlertDialog,
  AlertDialogPortal,
  AlertDialogOverlay,
  AlertDialogTrigger,
  AlertDialogContent,
  AlertDialogHeader,
  AlertDialogFooter,
  AlertDialogTitle,
  AlertDialogDescription,
  AlertDialogAction,
  AlertDialogCancel,
}

```

---

## `src/components/ui/alert.jsx`

```javascript
import * as React from "react"
import { cva } from "class-variance-authority";

import { cn } from "@/lib/utils"

const alertVariants = cva(
  "relative w-full rounded-lg border px-4 py-3 text-sm [&>svg+div]:translate-y-[-3px] [&>svg]:absolute [&>svg]:left-4 [&>svg]:top-4 [&>svg]:text-foreground [&>svg~*]:pl-7",
  {
    variants: {
      variant: {
        default: "bg-background text-foreground",
        destructive:
          "border-destructive/50 text-destructive dark:border-destructive [&>svg]:text-destructive",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
)

const Alert = React.forwardRef(({ className, variant, ...props }, ref) => (
  <div
    ref={ref}
    role="alert"
    className={cn(alertVariants({ variant }), className)}
    {...props} />
))
Alert.displayName = "Alert"

const AlertTitle = React.forwardRef(({ className, ...props }, ref) => (
  <h5
    ref={ref}
    className={cn("mb-1 font-medium leading-none tracking-tight", className)}
    {...props} />
))
AlertTitle.displayName = "AlertTitle"

const AlertDescription = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("text-sm [&_p]:leading-relaxed", className)}
    {...props} />
))
AlertDescription.displayName = "AlertDescription"

export { Alert, AlertTitle, AlertDescription }

```

---

## `src/components/ui/aspect-ratio.jsx`

```javascript
import * as AspectRatioPrimitive from "@radix-ui/react-aspect-ratio"

const AspectRatio = AspectRatioPrimitive.Root

export { AspectRatio }

```

---

## `src/components/ui/avatar.jsx`

```javascript
"use client"

import * as React from "react"
import * as AvatarPrimitive from "@radix-ui/react-avatar"

import { cn } from "@/lib/utils"

const Avatar = React.forwardRef(({ className, ...props }, ref) => (
  <AvatarPrimitive.Root
    ref={ref}
    className={cn("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full", className)}
    {...props} />
))
Avatar.displayName = AvatarPrimitive.Root.displayName

const AvatarImage = React.forwardRef(({ className, ...props }, ref) => (
  <AvatarPrimitive.Image
    ref={ref}
    className={cn("aspect-square h-full w-full", className)}
    {...props} />
))
AvatarImage.displayName = AvatarPrimitive.Image.displayName

const AvatarFallback = React.forwardRef(({ className, ...props }, ref) => (
  <AvatarPrimitive.Fallback
    ref={ref}
    className={cn(
      "flex h-full w-full items-center justify-center rounded-full bg-muted",
      className
    )}
    {...props} />
))
AvatarFallback.displayName = AvatarPrimitive.Fallback.displayName

export { Avatar, AvatarImage, AvatarFallback }

```

---

## `src/components/ui/badge.jsx`

```javascript
import * as React from "react"
import { cva } from "class-variance-authority";

import { cn } from "@/lib/utils"

const badgeVariants = cva(
  "inline-flex items-center rounded-md border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2",
  {
    variants: {
      variant: {
        default:
          "border-transparent bg-primary text-primary-foreground shadow hover:bg-primary/80",
        secondary:
          "border-transparent bg-secondary text-secondary-foreground hover:bg-secondary/80",
        destructive:
          "border-transparent bg-destructive text-destructive-foreground shadow hover:bg-destructive/80",
        outline: "text-foreground",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
)

function Badge({
  className,
  variant,
  ...props
}) {
  return (<div className={cn(badgeVariants({ variant }), className)} {...props} />);
}

export { Badge, badgeVariants }

```

---

## `src/components/ui/breadcrumb.jsx`

```javascript
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { ChevronRight, MoreHorizontal } from "lucide-react"

import { cn } from "@/lib/utils"

const Breadcrumb = React.forwardRef(
  ({ ...props }, ref) => <nav ref={ref} aria-label="breadcrumb" {...props} />
)
Breadcrumb.displayName = "Breadcrumb"

const BreadcrumbList = React.forwardRef(({ className, ...props }, ref) => (
  <ol
    ref={ref}
    className={cn(
      "flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",
      className
    )}
    {...props} />
))
BreadcrumbList.displayName = "BreadcrumbList"

const BreadcrumbItem = React.forwardRef(({ className, ...props }, ref) => (
  <li
    ref={ref}
    className={cn("inline-flex items-center gap-1.5", className)}
    {...props} />
))
BreadcrumbItem.displayName = "BreadcrumbItem"

const BreadcrumbLink = React.forwardRef(({ asChild, className, ...props }, ref) => {
  const Comp = asChild ? Slot : "a"

  return (
    (<Comp
      ref={ref}
      className={cn("transition-colors hover:text-foreground", className)}
      {...props} />)
  );
})
BreadcrumbLink.displayName = "BreadcrumbLink"

const BreadcrumbPage = React.forwardRef(({ className, ...props }, ref) => (
  <span
    ref={ref}
    role="link"
    aria-disabled="true"
    aria-current="page"
    className={cn("font-normal text-foreground", className)}
    {...props} />
))
BreadcrumbPage.displayName = "BreadcrumbPage"

const BreadcrumbSeparator = ({
  children,
  className,
  ...props
}) => (
  <li
    role="presentation"
    aria-hidden="true"
    className={cn("[&>svg]:w-3.5 [&>svg]:h-3.5", className)}
    {...props}>
    {children ?? <ChevronRight />}
  </li>
)
BreadcrumbSeparator.displayName = "BreadcrumbSeparator"

const BreadcrumbEllipsis = ({
  className,
  ...props
}) => (
  <span
    role="presentation"
    aria-hidden="true"
    className={cn("flex h-9 w-9 items-center justify-center", className)}
    {...props}>
    <MoreHorizontal className="h-4 w-4" />
    <span className="sr-only">More</span>
  </span>
)
BreadcrumbEllipsis.displayName = "BreadcrumbElipssis"

export {
  Breadcrumb,
  BreadcrumbList,
  BreadcrumbItem,
  BreadcrumbLink,
  BreadcrumbPage,
  BreadcrumbSeparator,
  BreadcrumbEllipsis,
}

```

---

## `src/components/ui/button.jsx`

```javascript
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva } from "class-variance-authority";

import { cn } from "@/lib/utils"

const buttonVariants = cva(
  "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  {
    variants: {
      variant: {
        default:
          "bg-primary text-primary-foreground shadow hover:bg-primary/90",
        destructive:
          "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
        outline:
          "border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",
        secondary:
          "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
        ghost: "hover:bg-accent hover:text-accent-foreground",
        link: "text-primary underline-offset-4 hover:underline",
      },
      size: {
        default: "h-9 px-4 py-2",
        sm: "h-8 rounded-md px-3 text-xs",
        lg: "h-10 rounded-md px-8",
        icon: "h-9 w-9",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

const Button = React.forwardRef(({ className, variant, size, asChild = false, ...props }, ref) => {
  const Comp = asChild ? Slot : "button"
  return (
    (<Comp
      className={cn(buttonVariants({ variant, size, className }))}
      ref={ref}
      {...props} />)
  );
})
Button.displayName = "Button"

export { Button, buttonVariants }

```

---

## `src/components/ui/calendar.jsx`

```javascript
import * as React from "react"
import { ChevronLeft, ChevronRight } from "lucide-react"
import { DayPicker } from "react-day-picker"

import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button"

function Calendar({
  className,
  classNames,
  showOutsideDays = true,
  ...props
}) {
  return (
    (<DayPicker
      showOutsideDays={showOutsideDays}
      className={cn("p-3", className)}
      classNames={{
        months: "flex flex-col sm:flex-row space-y-4 sm:space-x-4 sm:space-y-0",
        month: "space-y-4",
        caption: "flex justify-center pt-1 relative items-center",
        caption_label: "text-sm font-medium",
        nav: "space-x-1 flex items-center",
        nav_button: cn(
          buttonVariants({ variant: "outline" }),
          "h-7 w-7 bg-transparent p-0 opacity-50 hover:opacity-100"
        ),
        nav_button_previous: "absolute left-1",
        nav_button_next: "absolute right-1",
        table: "w-full border-collapse space-y-1",
        head_row: "flex",
        head_cell:
          "text-muted-foreground rounded-md w-8 font-normal text-[0.8rem]",
        row: "flex w-full mt-2",
        cell: cn(
          "relative p-0 text-center text-sm focus-within:relative focus-within:z-20 [&:has([aria-selected])]:bg-accent [&:has([aria-selected].day-outside)]:bg-accent/50 [&:has([aria-selected].day-range-end)]:rounded-r-md",
          props.mode === "range"
            ? "[&:has(>.day-range-end)]:rounded-r-md [&:has(>.day-range-start)]:rounded-l-md first:[&:has([aria-selected])]:rounded-l-md last:[&:has([aria-selected])]:rounded-r-md"
            : "[&:has([aria-selected])]:rounded-md"
        ),
        day: cn(
          buttonVariants({ variant: "ghost" }),
          "h-8 w-8 p-0 font-normal aria-selected:opacity-100"
        ),
        day_range_start: "day-range-start",
        day_range_end: "day-range-end",
        day_selected:
          "bg-primary text-primary-foreground hover:bg-primary hover:text-primary-foreground focus:bg-primary focus:text-primary-foreground",
        day_today: "bg-accent text-accent-foreground",
        day_outside:
          "day-outside text-muted-foreground aria-selected:bg-accent/50 aria-selected:text-muted-foreground",
        day_disabled: "text-muted-foreground opacity-50",
        day_range_middle:
          "aria-selected:bg-accent aria-selected:text-accent-foreground",
        day_hidden: "invisible",
        ...classNames,
      }}
      components={{
        IconLeft: ({ className, ...props }) => (
          <ChevronLeft className={cn("h-4 w-4", className)} {...props} />
        ),
        IconRight: ({ className, ...props }) => (
          <ChevronRight className={cn("h-4 w-4", className)} {...props} />
        ),
      }}
      {...props} />)
  );
}
Calendar.displayName = "Calendar"

export { Calendar }

```

---

## `src/components/ui/card.jsx`

```javascript
import * as React from "react"

import { cn } from "@/lib/utils"

const Card = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("rounded-xl border bg-card text-card-foreground shadow", className)}
    {...props} />
))
Card.displayName = "Card"

const CardHeader = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("flex flex-col space-y-1.5 p-6", className)}
    {...props} />
))
CardHeader.displayName = "CardHeader"

const CardTitle = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("font-semibold leading-none tracking-tight", className)}
    {...props} />
))
CardTitle.displayName = "CardTitle"

const CardDescription = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    {...props} />
))
CardDescription.displayName = "CardDescription"

const CardContent = React.forwardRef(({ className, ...props }, ref) => (
  <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
))
CardContent.displayName = "CardContent"

const CardFooter = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    className={cn("flex items-center p-6 pt-0", className)}
    {...props} />
))
CardFooter.displayName = "CardFooter"

export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }

```

---

## `src/components/ui/carousel.jsx`

```javascript
import * as React from "react"
import useEmblaCarousel from "embla-carousel-react";
import { ArrowLeft, ArrowRight } from "lucide-react"

import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"

const CarouselContext = React.createContext(null)

function useCarousel() {
  const context = React.useContext(CarouselContext)

  if (!context) {
    throw new Error("useCarousel must be used within a <Carousel />")
  }

  return context
}

const Carousel = React.forwardRef((
  {
    orientation = "horizontal",
    opts,
    setApi,
    plugins,
    className,
    children,
    ...props
  },
  ref
) => {
  const [carouselRef, api] = useEmblaCarousel({
    ...opts,
    axis: orientation === "horizontal" ? "x" : "y",
  }, plugins)
  const [canScrollPrev, setCanScrollPrev] = React.useState(false)
  const [canScrollNext, setCanScrollNext] = React.useState(false)

  const onSelect = React.useCallback((api) => {
    if (!api) {
      return
    }

    setCanScrollPrev(api.canScrollPrev())
    setCanScrollNext(api.canScrollNext())
  }, [])

  const scrollPrev = React.useCallback(() => {
    api?.scrollPrev()
  }, [api])

  const scrollNext = React.useCallback(() => {
    api?.scrollNext()
  }, [api])

  const handleKeyDown = React.useCallback((event) => {
    if (event.key === "ArrowLeft") {
      event.preventDefault()
      scrollPrev()
    } else if (event.key === "ArrowRight") {
      event.preventDefault()
      scrollNext()
    }
  }, [scrollPrev, scrollNext])

  React.useEffect(() => {
    if (!api || !setApi) {
      return
    }

    setApi(api)
  }, [api, setApi])

  React.useEffect(() => {
    if (!api) {
      return
    }

    onSelect(api)
    api.on("reInit", onSelect)
    api.on("select", onSelect)

    return () => {
      api?.off("select", onSelect)
    };
  }, [api, onSelect])

  return (
    (<CarouselContext.Provider
      value={{
        carouselRef,
        api: api,
        opts,
        orientation:
          orientation || (opts?.axis === "y" ? "vertical" : "horizontal"),
        scrollPrev,
        scrollNext,
        canScrollPrev,
        canScrollNext,
      }}>
      <div
        ref={ref}
        onKeyDownCapture={handleKeyDown}
        className={cn("relative", className)}
        role="region"
        aria-roledescription="carousel"
        {...props}>
        {children}
      </div>
    </CarouselContext.Provider>)
  );
})
Carousel.displayName = "Carousel"

const CarouselContent = React.forwardRef(({ className, ...props }, ref) => {
  const { carouselRef, orientation } = useCarousel()

  return (
    (<div ref={carouselRef} className="overflow-hidden">
      <div
        ref={ref}
        className={cn(
          "flex",
          orientation === "horizontal" ? "-ml-4" : "-mt-4 flex-col",
          className
        )}
        {...props} />
    </div>)
  );
})
CarouselContent.displayName = "CarouselContent"

const CarouselItem = React.forwardRef(({ className, ...props }, ref) => {
  const { orientation } = useCarousel()

  return (
    (<div
      ref={ref}
      role="group"
      aria-roledescription="slide"
      className={cn(
        "min-w-0 shrink-0 grow-0 basis-full",
        orientation === "horizontal" ? "pl-4" : "pt-4",
        className
      )}
      {...props} />)
  );
})
CarouselItem.displayName = "CarouselItem"

const CarouselPrevious = React.forwardRef(({ className, variant = "outline", size = "icon", ...props }, ref) => {
  const { orientation, scrollPrev, canScrollPrev } = useCarousel()

  return (
    (<Button
      ref={ref}
      variant={variant}
      size={size}
      className={cn("absolute  h-8 w-8 rounded-full", orientation === "horizontal"
        ? "-left-12 top-1/2 -translate-y-1/2"
        : "-top-12 left-1/2 -translate-x-1/2 rotate-90", className)}
      disabled={!canScrollPrev}
      onClick={scrollPrev}
      {...props}>
      <ArrowLeft className="h-4 w-4" />
      <span className="sr-only">Previous slide</span>
    </Button>)
  );
})
CarouselPrevious.displayName = "CarouselPrevious"

const CarouselNext = React.forwardRef(({ className, variant = "outline", size = "icon", ...props }, ref) => {
  const { orientation, scrollNext, canScrollNext } = useCarousel()

  return (
    (<Button
      ref={ref}
      variant={variant}
      size={size}
      className={cn("absolute h-8 w-8 rounded-full", orientation === "horizontal"
        ? "-right-12 top-1/2 -translate-y-1/2"
        : "-bottom-12 left-1/2 -translate-x-1/2 rotate-90", className)}
      disabled={!canScrollNext}
      onClick={scrollNext}
      {...props}>
      <ArrowRight className="h-4 w-4" />
      <span className="sr-only">Next slide</span>
    </Button>)
  );
})
CarouselNext.displayName = "CarouselNext"

export { Carousel, CarouselContent, CarouselItem, CarouselPrevious, CarouselNext };

```

---

## `src/components/ui/chart.jsx`

```javascript
"use client";
import * as React from "react"
import * as RechartsPrimitive from "recharts"

import { cn } from "@/lib/utils"

// Format: { THEME_NAME: CSS_SELECTOR }
const THEMES = {
  light: "",
  dark: ".dark"
}

const ChartContext = React.createContext(null)

function useChart() {
  const context = React.useContext(ChartContext)

  if (!context) {
    throw new Error("useChart must be used within a <ChartContainer />")
  }

  return context
}

const ChartContainer = React.forwardRef(({ id, className, children, config, ...props }, ref) => {
  const uniqueId = React.useId()
  const chartId = `chart-${id || uniqueId.replace(/:/g, "")}`

  return (
    (<ChartContext.Provider value={{ config }}>
      <div
        data-chart={chartId}
        ref={ref}
        className={cn(
          "flex aspect-video justify-center text-xs [&_.recharts-cartesian-axis-tick_text]:fill-muted-foreground [&_.recharts-cartesian-grid_line[stroke='hsl(var(--muted))']]:stroke-border/50 [&_.recharts-curve.recharts-tooltip-cursor]:stroke-border [&_.recharts-dot[stroke='hsl(var(--background))']]:stroke-transparent [&_.recharts-layer]:outline-none [&_.recharts-polar-grid_[stroke='hsl(var(--muted))']]:stroke-border [&_.recharts-radial-bar-background-sector]:fill-muted [&_.recharts-rectangle.recharts-tooltip-cursor]:fill-muted [&_.recharts-reference-line_[stroke='hsl(var(--muted))']]:stroke-border [&_.recharts-sector[stroke='hsl(var(--background))']]:stroke-transparent [&_.recharts-sector]:outline-none [&_.recharts-surface]:outline-none",
          className
        )}
        {...props}>
        <ChartStyle id={chartId} config={config} />
        <RechartsPrimitive.ResponsiveContainer>
          {children}
        </RechartsPrimitive.ResponsiveContainer>
      </div>
    </ChartContext.Provider>)
  );
})
ChartContainer.displayName = "Chart"

const ChartStyle = ({
  id,
  config
}) => {
  const colorConfig = Object.entries(config).filter(([, config]) => config.theme || config.color)

  if (!colorConfig.length) {
    return null
  }

  return (
    (<style
      dangerouslySetInnerHTML={{
        __html: Object.entries(THEMES)
          .map(([theme, prefix]) => `
${prefix} [data-chart=${id}] {
${colorConfig
.map(([key, itemConfig]) => {
const color =
  itemConfig.theme?.[theme] ||
  itemConfig.color
return color ? `  --color-${key}: ${color};` : null
})
.join("\n")}
}
`)
          .join("\n"),
      }} />)
  );
}

const ChartTooltip = RechartsPrimitive.Tooltip

const ChartTooltipContent = React.forwardRef((
  {
    active,
    payload,
    className,
    indicator = "dot",
    hideLabel = false,
    hideIndicator = false,
    label,
    labelFormatter,
    labelClassName,
    formatter,
    color,
    nameKey,
    labelKey,
  },
  ref
) => {
  const { config } = useChart()

  const tooltipLabel = React.useMemo(() => {
    if (hideLabel || !payload?.length) {
      return null
    }

    const [item] = payload
    const key = `${labelKey || item.dataKey || item.name || "value"}`
    const itemConfig = getPayloadConfigFromPayload(config, item, key)
    const value =
      !labelKey && typeof label === "string"
        ? config[label]?.label || label
        : itemConfig?.label

    if (labelFormatter) {
      return (
        (<div className={cn("font-medium", labelClassName)}>
          {labelFormatter(value, payload)}
        </div>)
      );
    }

    if (!value) {
      return null
    }

    return <div className={cn("font-medium", labelClassName)}>{value}</div>;
  }, [
    label,
    labelFormatter,
    payload,
    hideLabel,
    labelClassName,
    config,
    labelKey,
  ])

  if (!active || !payload?.length) {
    return null
  }

  const nestLabel = payload.length === 1 && indicator !== "dot"

  return (
    (<div
      ref={ref}
      className={cn(
        "grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",
        className
      )}>
      {!nestLabel ? tooltipLabel : null}
      <div className="grid gap-1.5">
        {payload.map((item, index) => {
          const key = `${nameKey || item.name || item.dataKey || "value"}`
          const itemConfig = getPayloadConfigFromPayload(config, item, key)
          const indicatorColor = color || item.payload.fill || item.color

          return (
            (<div
              key={item.dataKey}
              className={cn(
                "flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",
                indicator === "dot" && "items-center"
              )}>
              {formatter && item?.value !== undefined && item.name ? (
                formatter(item.value, item.name, item, index, item.payload)
              ) : (
                <>
                  {itemConfig?.icon ? (
                    <itemConfig.icon />
                  ) : (
                    !hideIndicator && (
                      <div
                        className={cn("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]", {
                          "h-2.5 w-2.5": indicator === "dot",
                          "w-1": indicator === "line",
                          "w-0 border-[1.5px] border-dashed bg-transparent":
                            indicator === "dashed",
                          "my-0.5": nestLabel && indicator === "dashed",
                        })}
                        style={
                          {
                            "--color-bg": indicatorColor,
                            "--color-border": indicatorColor
                          }
                        } />
                    )
                  )}
                  <div
                    className={cn(
                      "flex flex-1 justify-between leading-none",
                      nestLabel ? "items-end" : "items-center"
                    )}>
                    <div className="grid gap-1.5">
                      {nestLabel ? tooltipLabel : null}
                      <span className="text-muted-foreground">
                        {itemConfig?.label || item.name}
                      </span>
                    </div>
                    {item.value && (
                      <span className="font-mono font-medium tabular-nums text-foreground">
                        {item.value.toLocaleString()}
                      </span>
                    )}
                  </div>
                </>
              )}
            </div>)
          );
        })}
      </div>
    </div>)
  );
})
ChartTooltipContent.displayName = "ChartTooltip"

const ChartLegend = RechartsPrimitive.Legend

const ChartLegendContent = React.forwardRef((
  { className, hideIcon = false, payload, verticalAlign = "bottom", nameKey },
  ref
) => {
  const { config } = useChart()

  if (!payload?.length) {
    return null
  }

  return (
    (<div
      ref={ref}
      className={cn(
        "flex items-center justify-center gap-4",
        verticalAlign === "top" ? "pb-3" : "pt-3",
        className
      )}>
      {payload.map((item) => {
        const key = `${nameKey || item.dataKey || "value"}`
        const itemConfig = getPayloadConfigFromPayload(config, item, key)

        return (
          (<div
            key={item.value}
            className={cn(
              "flex items-center gap-1.5 [&>svg]:h-3 [&>svg]:w-3 [&>svg]:text-muted-foreground"
            )}>
            {itemConfig?.icon && !hideIcon ? (
              <itemConfig.icon />
            ) : (
              <div
                className="h-2 w-2 shrink-0 rounded-[2px]"
                style={{
                  backgroundColor: item.color,
                }} />
            )}
            {itemConfig?.label}
          </div>)
        );
      })}
    </div>)
  );
})
ChartLegendContent.displayName = "ChartLegend"

// Helper to extract item config from a payload.
function getPayloadConfigFromPayload(
  config,
  payload,
  key
) {
  if (typeof payload !== "object" || payload === null) {
    return undefined
  }

  const payloadPayload =
    "payload" in payload &&
    typeof payload.payload === "object" &&
    payload.payload !== null
      ? payload.payload
      : undefined

  let configLabelKey = key

  if (
    key in payload &&
    typeof payload[key] === "string"
  ) {
    configLabelKey = payload[key]
  } else if (
    payloadPayload &&
    key in payloadPayload &&
    typeof payloadPayload[key] === "string"
  ) {
    configLabelKey = payloadPayload[key]
  }

  return configLabelKey in config
    ? config[configLabelKey]
    : config[key];
}

export {
  ChartContainer,
  ChartTooltip,
  ChartTooltipContent,
  ChartLegend,
  ChartLegendContent,
  ChartStyle,
}

```

---

## `src/components/ui/checkbox.jsx`

```javascript
import * as React from "react"
import * as CheckboxPrimitive from "@radix-ui/react-checkbox"
import { Check } from "lucide-react"

import { cn } from "@/lib/utils"

const Checkbox = React.forwardRef(({ className, ...props }, ref) => (
  <CheckboxPrimitive.Root
    ref={ref}
    className={cn(
      "peer h-4 w-4 shrink-0 rounded-sm border border-primary shadow focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
      className
    )}
    {...props}>
    <CheckboxPrimitive.Indicator className={cn("flex items-center justify-center text-current")}>
      <Check className="h-4 w-4" />
    </CheckboxPrimitive.Indicator>
  </CheckboxPrimitive.Root>
))
Checkbox.displayName = CheckboxPrimitive.Root.displayName

export { Checkbox }

```

---

## `src/components/ui/collapsible.jsx`

```javascript
"use client"

import * as CollapsiblePrimitive from "@radix-ui/react-collapsible"

const Collapsible = CollapsiblePrimitive.Root

const CollapsibleTrigger = CollapsiblePrimitive.CollapsibleTrigger

const CollapsibleContent = CollapsiblePrimitive.CollapsibleContent

export { Collapsible, CollapsibleTrigger, CollapsibleContent }

```

---

## `src/components/ui/command.jsx`

```javascript
import * as React from "react"
import { Command as CommandPrimitive } from "cmdk"
import { Search } from "lucide-react"

import { cn } from "@/lib/utils"
import { Dialog, DialogContent } from "@/components/ui/dialog"

const Command = React.forwardRef(({ className, ...props }, ref) => (
  <CommandPrimitive
    ref={ref}
    className={cn(
      "flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",
      className
    )}
    {...props} />
))
Command.displayName = CommandPrimitive.displayName

const CommandDialog = ({
  children,
  ...props
}) => {
  return (
    (<Dialog {...props}>
      <DialogContent className="overflow-hidden p-0">
        <Command
          className="[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground [&_[cmdk-group]:not([hidden])_~[cmdk-group]]:pt-0 [&_[cmdk-group]]:px-2 [&_[cmdk-input-wrapper]_svg]:h-5 [&_[cmdk-input-wrapper]_svg]:w-5 [&_[cmdk-input]]:h-12 [&_[cmdk-item]]:px-2 [&_[cmdk-item]]:py-3 [&_[cmdk-item]_svg]:h-5 [&_[cmdk-item]_svg]:w-5">
          {children}
        </Command>
      </DialogContent>
    </Dialog>)
  );
}

const CommandInput = React.forwardRef(({ className, ...props }, ref) => (
  <div className="flex items-center border-b px-3" cmdk-input-wrapper="">
    <Search className="mr-2 h-4 w-4 shrink-0 opacity-50" />
    <CommandPrimitive.Input
      ref={ref}
      className={cn(
        "flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground disabled:cursor-not-allowed disabled:opacity-50",
        className
      )}
      {...props} />
  </div>
))

CommandInput.displayName = CommandPrimitive.Input.displayName

const CommandList = React.forwardRef(({ className, ...props }, ref) => (
  <CommandPrimitive.List
    ref={ref}
    className={cn("max-h-[300px] overflow-y-auto overflow-x-hidden", className)}
    {...props} />
))

CommandList.displayName = CommandPrimitive.List.displayName

const CommandEmpty = React.forwardRef((props, ref) => (
  <CommandPrimitive.Empty ref={ref} className="py-6 text-center text-sm" {...props} />
))

CommandEmpty.displayName = CommandPrimitive.Empty.displayName

const CommandGroup = React.forwardRef(({ className, ...props }, ref) => (
  <CommandPrimitive.Group
    ref={ref}
    className={cn(
      "overflow-hidden p-1 text-foreground [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium [&_[cmdk-group-heading]]:text-muted-foreground",
      className
    )}
    {...props} />
))

CommandGroup.displayName = CommandPrimitive.Group.displayName

const CommandSeparator = React.forwardRef(({ className, ...props }, ref) => (
  <CommandPrimitive.Separator ref={ref} className={cn("-mx-1 h-px bg-border", className)} {...props} />
))
CommandSeparator.displayName = CommandPrimitive.Separator.displayName

const CommandItem = React.forwardRef(({ className, ...props }, ref) => (
  <CommandPrimitive.Item
    ref={ref}
    className={cn(
      "relative flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
      className
    )}
    {...props} />
))

CommandItem.displayName = CommandPrimitive.Item.displayName

const CommandShortcut = ({
  className,
  ...props
}) => {
  return (
    (<span
      className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)}
      {...props} />)
  );
}
CommandShortcut.displayName = "CommandShortcut"

export {
  Command,
  CommandDialog,
  CommandInput,
  CommandList,
  CommandEmpty,
  CommandGroup,
  CommandItem,
  CommandShortcut,
  CommandSeparator,
}

```

---

## `src/components/ui/context-menu.jsx`

```javascript
import * as React from "react"
import * as ContextMenuPrimitive from "@radix-ui/react-context-menu"
import { Check, ChevronRight, Circle } from "lucide-react"

import { cn } from "@/lib/utils"

const ContextMenu = ContextMenuPrimitive.Root

const ContextMenuTrigger = ContextMenuPrimitive.Trigger

const ContextMenuGroup = ContextMenuPrimitive.Group

const ContextMenuPortal = ContextMenuPrimitive.Portal

const ContextMenuSub = ContextMenuPrimitive.Sub

const ContextMenuRadioGroup = ContextMenuPrimitive.RadioGroup

const ContextMenuSubTrigger = React.forwardRef(({ className, inset, children, ...props }, ref) => (
  <ContextMenuPrimitive.SubTrigger
    ref={ref}
    className={cn(
      "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
      inset && "pl-8",
      className
    )}
    {...props}>
    {children}
    <ChevronRight className="ml-auto h-4 w-4" />
  </ContextMenuPrimitive.SubTrigger>
))
ContextMenuSubTrigger.displayName = ContextMenuPrimitive.SubTrigger.displayName

const ContextMenuSubContent = React.forwardRef(({ className, ...props }, ref) => (
  <ContextMenuPrimitive.SubContent
    ref={ref}
    className={cn(
      "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    )}
    {...props} />
))
ContextMenuSubContent.displayName = ContextMenuPrimitive.SubContent.displayName

const ContextMenuContent = React.forwardRef(({ className, ...props }, ref) => (
  <ContextMenuPrimitive.Portal>
    <ContextMenuPrimitive.Content
      ref={ref}
      className={cn(
        "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
        className
      )}
      {...props} />
  </ContextMenuPrimitive.Portal>
))
ContextMenuContent.displayName = ContextMenuPrimitive.Content.displayName

const ContextMenuItem = React.forwardRef(({ className, inset, ...props }, ref) => (
  <ContextMenuPrimitive.Item
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      inset && "pl-8",
      className
    )}
    {...props} />
))
ContextMenuItem.displayName = ContextMenuPrimitive.Item.displayName

const ContextMenuCheckboxItem = React.forwardRef(({ className, children, checked, ...props }, ref) => (
  <ContextMenuPrimitive.CheckboxItem
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    )}
    checked={checked}
    {...props}>
    <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
      <ContextMenuPrimitive.ItemIndicator>
        <Check className="h-4 w-4" />
      </ContextMenuPrimitive.ItemIndicator>
    </span>
    {children}
  </ContextMenuPrimitive.CheckboxItem>
))
ContextMenuCheckboxItem.displayName =
  ContextMenuPrimitive.CheckboxItem.displayName

const ContextMenuRadioItem = React.forwardRef(({ className, children, ...props }, ref) => (
  <ContextMenuPrimitive.RadioItem
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    )}
    {...props}>
    <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
      <ContextMenuPrimitive.ItemIndicator>
        <Circle className="h-4 w-4 fill-current" />
      </ContextMenuPrimitive.ItemIndicator>
    </span>
    {children}
  </ContextMenuPrimitive.RadioItem>
))
ContextMenuRadioItem.displayName = ContextMenuPrimitive.RadioItem.displayName

const ContextMenuLabel = React.forwardRef(({ className, inset, ...props }, ref) => (
  <ContextMenuPrimitive.Label
    ref={ref}
    className={cn(
      "px-2 py-1.5 text-sm font-semibold text-foreground",
      inset && "pl-8",
      className
    )}
    {...props} />
))
ContextMenuLabel.displayName = ContextMenuPrimitive.Label.displayName

const ContextMenuSeparator = React.forwardRef(({ className, ...props }, ref) => (
  <ContextMenuPrimitive.Separator
    ref={ref}
    className={cn("-mx-1 my-1 h-px bg-border", className)}
    {...props} />
))
ContextMenuSeparator.displayName = ContextMenuPrimitive.Separator.displayName

const ContextMenuShortcut = ({
  className,
  ...props
}) => {
  return (
    (<span
      className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)}
      {...props} />)
  );
}
ContextMenuShortcut.displayName = "ContextMenuShortcut"

export {
  ContextMenu,
  ContextMenuTrigger,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuCheckboxItem,
  ContextMenuRadioItem,
  ContextMenuLabel,
  ContextMenuSeparator,
  ContextMenuShortcut,
  ContextMenuGroup,
  ContextMenuPortal,
  ContextMenuSub,
  ContextMenuSubContent,
  ContextMenuSubTrigger,
  ContextMenuRadioGroup,
}

```

---

## `src/components/ui/dialog.jsx`

```javascript
"use client"

import * as React from "react"
import * as DialogPrimitive from "@radix-ui/react-dialog"
import { X } from "lucide-react"

import { cn } from "@/lib/utils"

const Dialog = DialogPrimitive.Root

const DialogTrigger = DialogPrimitive.Trigger

const DialogPortal = DialogPrimitive.Portal

const DialogClose = DialogPrimitive.Close

const DialogOverlay = React.forwardRef(({ className, ...props }, ref) => (
  <DialogPrimitive.Overlay
    ref={ref}
    className={cn(
      "fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
      className
    )}
    {...props} />
))
DialogOverlay.displayName = DialogPrimitive.Overlay.displayName

const DialogContent = React.forwardRef(({ className, children, ...props }, ref) => (
  <DialogPortal>
    <DialogOverlay />
    <DialogPrimitive.Content
      ref={ref}
      className={cn(
        "fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
        className
      )}
      {...props}>
      {children}
      <DialogPrimitive.Close
        className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
        <X className="h-4 w-4" />
        <span className="sr-only">Close</span>
      </DialogPrimitive.Close>
    </DialogPrimitive.Content>
  </DialogPortal>
))
DialogContent.displayName = DialogPrimitive.Content.displayName

const DialogHeader = ({
  className,
  ...props
}) => (
  <div
    className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)}
    {...props} />
)
DialogHeader.displayName = "DialogHeader"

const DialogFooter = ({
  className,
  ...props
}) => (
  <div
    className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
    {...props} />
)
DialogFooter.displayName = "DialogFooter"

const DialogTitle = React.forwardRef(({ className, ...props }, ref) => (
  <DialogPrimitive.Title
    ref={ref}
    className={cn("text-lg font-semibold leading-none tracking-tight", className)}
    {...props} />
))
DialogTitle.displayName = DialogPrimitive.Title.displayName

const DialogDescription = React.forwardRef(({ className, ...props }, ref) => (
  <DialogPrimitive.Description
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    {...props} />
))
DialogDescription.displayName = DialogPrimitive.Description.displayName

export {
  Dialog,
  DialogPortal,
  DialogOverlay,
  DialogTrigger,
  DialogClose,
  DialogContent,
  DialogHeader,
  DialogFooter,
  DialogTitle,
  DialogDescription,
}

```

---

## `src/components/ui/drawer.jsx`

```javascript
"use client"

import * as React from "react"
import { Drawer as DrawerPrimitive } from "vaul"

import { cn } from "@/lib/utils"

const Drawer = ({
  shouldScaleBackground = true,
  ...props
}) => (
  <DrawerPrimitive.Root shouldScaleBackground={shouldScaleBackground} {...props} />
)
Drawer.displayName = "Drawer"

const DrawerTrigger = DrawerPrimitive.Trigger

const DrawerPortal = DrawerPrimitive.Portal

const DrawerClose = DrawerPrimitive.Close

const DrawerOverlay = React.forwardRef(({ className, ...props }, ref) => (
  <DrawerPrimitive.Overlay
    ref={ref}
    className={cn("fixed inset-0 z-50 bg-black/80", className)}
    {...props} />
))
DrawerOverlay.displayName = DrawerPrimitive.Overlay.displayName

const DrawerContent = React.forwardRef(({ className, children, ...props }, ref) => (
  <DrawerPortal>
    <DrawerOverlay />
    <DrawerPrimitive.Content
      ref={ref}
      className={cn(
        "fixed inset-x-0 bottom-0 z-50 mt-24 flex h-auto flex-col rounded-t-[10px] border bg-background",
        className
      )}
      {...props}>
      <div className="mx-auto mt-4 h-2 w-[100px] rounded-full bg-muted" />
      {children}
    </DrawerPrimitive.Content>
  </DrawerPortal>
))
DrawerContent.displayName = "DrawerContent"

const DrawerHeader = ({
  className,
  ...props
}) => (
  <div
    className={cn("grid gap-1.5 p-4 text-center sm:text-left", className)}
    {...props} />
)
DrawerHeader.displayName = "DrawerHeader"

const DrawerFooter = ({
  className,
  ...props
}) => (
  <div className={cn("mt-auto flex flex-col gap-2 p-4", className)} {...props} />
)
DrawerFooter.displayName = "DrawerFooter"

const DrawerTitle = React.forwardRef(({ className, ...props }, ref) => (
  <DrawerPrimitive.Title
    ref={ref}
    className={cn("text-lg font-semibold leading-none tracking-tight", className)}
    {...props} />
))
DrawerTitle.displayName = DrawerPrimitive.Title.displayName

const DrawerDescription = React.forwardRef(({ className, ...props }, ref) => (
  <DrawerPrimitive.Description
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    {...props} />
))
DrawerDescription.displayName = DrawerPrimitive.Description.displayName

export {
  Drawer,
  DrawerPortal,
  DrawerOverlay,
  DrawerTrigger,
  DrawerClose,
  DrawerContent,
  DrawerHeader,
  DrawerFooter,
  DrawerTitle,
  DrawerDescription,
}

```

---

## `src/components/ui/dropdown-menu.jsx`

```javascript
import * as React from "react"
import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
import { Check, ChevronRight, Circle } from "lucide-react"

import { cn } from "@/lib/utils"

const DropdownMenu = DropdownMenuPrimitive.Root

const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger

const DropdownMenuGroup = DropdownMenuPrimitive.Group

const DropdownMenuPortal = DropdownMenuPrimitive.Portal

const DropdownMenuSub = DropdownMenuPrimitive.Sub

const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup

const DropdownMenuSubTrigger = React.forwardRef(({ className, inset, children, ...props }, ref) => (
  <DropdownMenuPrimitive.SubTrigger
    ref={ref}
    className={cn(
      "flex cursor-default gap-2 select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
      inset && "pl-8",
      className
    )}
    {...props}>
    {children}
    <ChevronRight className="ml-auto" />
  </DropdownMenuPrimitive.SubTrigger>
))
DropdownMenuSubTrigger.displayName =
  DropdownMenuPrimitive.SubTrigger.displayName

const DropdownMenuSubContent = React.forwardRef(({ className, ...props }, ref) => (
  <DropdownMenuPrimitive.SubContent
    ref={ref}
    className={cn(
      "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    )}
    {...props} />
))
DropdownMenuSubContent.displayName =
  DropdownMenuPrimitive.SubContent.displayName

const DropdownMenuContent = React.forwardRef(({ className, sideOffset = 4, ...props }, ref) => (
  <DropdownMenuPrimitive.Portal>
    <DropdownMenuPrimitive.Content
      ref={ref}
      sideOffset={sideOffset}
      className={cn(
        "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
        "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
        className
      )}
      {...props} />
  </DropdownMenuPrimitive.Portal>
))
DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName

const DropdownMenuItem = React.forwardRef(({ className, inset, ...props }, ref) => (
  <DropdownMenuPrimitive.Item
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
      inset && "pl-8",
      className
    )}
    {...props} />
))
DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName

const DropdownMenuCheckboxItem = React.forwardRef(({ className, children, checked, ...props }, ref) => (
  <DropdownMenuPrimitive.CheckboxItem
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    )}
    checked={checked}
    {...props}>
    <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
      <DropdownMenuPrimitive.ItemIndicator>
        <Check className="h-4 w-4" />
      </DropdownMenuPrimitive.ItemIndicator>
    </span>
    {children}
  </DropdownMenuPrimitive.CheckboxItem>
))
DropdownMenuCheckboxItem.displayName =
  DropdownMenuPrimitive.CheckboxItem.displayName

const DropdownMenuRadioItem = React.forwardRef(({ className, children, ...props }, ref) => (
  <DropdownMenuPrimitive.RadioItem
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    )}
    {...props}>
    <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
      <DropdownMenuPrimitive.ItemIndicator>
        <Circle className="h-2 w-2 fill-current" />
      </DropdownMenuPrimitive.ItemIndicator>
    </span>
    {children}
  </DropdownMenuPrimitive.RadioItem>
))
DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName

const DropdownMenuLabel = React.forwardRef(({ className, inset, ...props }, ref) => (
  <DropdownMenuPrimitive.Label
    ref={ref}
    className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
    {...props} />
))
DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName

const DropdownMenuSeparator = React.forwardRef(({ className, ...props }, ref) => (
  <DropdownMenuPrimitive.Separator
    ref={ref}
    className={cn("-mx-1 my-1 h-px bg-muted", className)}
    {...props} />
))
DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName

const DropdownMenuShortcut = ({
  className,
  ...props
}) => {
  return (
    (<span
      className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
      {...props} />)
  );
}
DropdownMenuShortcut.displayName = "DropdownMenuShortcut"

export {
  DropdownMenu,
  DropdownMenuTrigger,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuCheckboxItem,
  DropdownMenuRadioItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuShortcut,
  DropdownMenuGroup,
  DropdownMenuPortal,
  DropdownMenuSub,
  DropdownMenuSubContent,
  DropdownMenuSubTrigger,
  DropdownMenuRadioGroup,
}

```

---

## `src/components/ui/form.jsx`

```javascript
"use client";
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { Controller, FormProvider, useFormContext } from "react-hook-form";

import { cn } from "@/lib/utils"
import { Label } from "@/components/ui/label"

const Form = FormProvider

const FormFieldContext = React.createContext({})

const FormField = (
  {
    ...props
  }
) => {
  return (
    (<FormFieldContext.Provider value={{ name: props.name }}>
      <Controller {...props} />
    </FormFieldContext.Provider>)
  );
}

const useFormField = () => {
  const fieldContext = React.useContext(FormFieldContext)
  const itemContext = React.useContext(FormItemContext)
  const { getFieldState, formState } = useFormContext()

  const fieldState = getFieldState(fieldContext.name, formState)

  if (!fieldContext) {
    throw new Error("useFormField should be used within <FormField>")
  }

  const { id } = itemContext

  return {
    id,
    name: fieldContext.name,
    formItemId: `${id}-form-item`,
    formDescriptionId: `${id}-form-item-description`,
    formMessageId: `${id}-form-item-message`,
    ...fieldState,
  }
}

const FormItemContext = React.createContext({})

const FormItem = React.forwardRef(({ className, ...props }, ref) => {
  const id = React.useId()

  return (
    (<FormItemContext.Provider value={{ id }}>
      <div ref={ref} className={cn("space-y-2", className)} {...props} />
    </FormItemContext.Provider>)
  );
})
FormItem.displayName = "FormItem"

const FormLabel = React.forwardRef(({ className, ...props }, ref) => {
  const { error, formItemId } = useFormField()

  return (
    (<Label
      ref={ref}
      className={cn(error && "text-destructive", className)}
      htmlFor={formItemId}
      {...props} />)
  );
})
FormLabel.displayName = "FormLabel"

const FormControl = React.forwardRef(({ ...props }, ref) => {
  const { error, formItemId, formDescriptionId, formMessageId } = useFormField()

  return (
    (<Slot
      ref={ref}
      id={formItemId}
      aria-describedby={
        !error
          ? `${formDescriptionId}`
          : `${formDescriptionId} ${formMessageId}`
      }
      aria-invalid={!!error}
      {...props} />)
  );
})
FormControl.displayName = "FormControl"

const FormDescription = React.forwardRef(({ className, ...props }, ref) => {
  const { formDescriptionId } = useFormField()

  return (
    (<p
      ref={ref}
      id={formDescriptionId}
      className={cn("text-[0.8rem] text-muted-foreground", className)}
      {...props} />)
  );
})
FormDescription.displayName = "FormDescription"

const FormMessage = React.forwardRef(({ className, children, ...props }, ref) => {
  const { error, formMessageId } = useFormField()
  const body = error ? String(error?.message) : children

  if (!body) {
    return null
  }

  return (
    (<p
      ref={ref}
      id={formMessageId}
      className={cn("text-[0.8rem] font-medium text-destructive", className)}
      {...props}>
      {body}
    </p>)
  );
})
FormMessage.displayName = "FormMessage"

export {
  useFormField,
  Form,
  FormItem,
  FormLabel,
  FormControl,
  FormDescription,
  FormMessage,
  FormField,
}

```

---

## `src/components/ui/hover-card.jsx`

```javascript
"use client"

import * as React from "react"
import * as HoverCardPrimitive from "@radix-ui/react-hover-card"

import { cn } from "@/lib/utils"

const HoverCard = HoverCardPrimitive.Root

const HoverCardTrigger = HoverCardPrimitive.Trigger

const HoverCardContent = React.forwardRef(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
  <HoverCardPrimitive.Content
    ref={ref}
    align={align}
    sideOffset={sideOffset}
    className={cn(
      "z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    )}
    {...props} />
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName

export { HoverCard, HoverCardTrigger, HoverCardContent }

```

---

## `src/components/ui/image-helpers.js`

```javascript
const WIX_MEDIA_HOSTS = {
  "media.base44.com": "/images/public/",
  "static.wixstatic.com": "/media/",
}

export const DEFAULT_TRANSFORM_WIDTH = 1024
export const IMAGE_LOAD_MODE = {
  OPTIMIZED: "optimized",
  ORIGINAL: "original",
  FALLBACK: "fallback",
}

const DEVICE_PIXEL_RATIOS = [1, 2, 3]
const MAX_DIMENSION = 6000

/** Returns transform metadata only for canonical public Wix image URLs. */
export function parseWixMediaUrl(src) {
  try {
    const url = new URL(src)
    if (
      url.protocol !== "https:" ||
      url.username ||
      url.password ||
      (url.port && url.port !== "443")
    ) {
      return null
    }

    const pathPrefix = WIX_MEDIA_HOSTS[url.hostname]
    if (!pathPrefix) return null

    const transformed = url.pathname.match(/^(.*)\/v1\/(?:fill|fit)\/[^/]+\/[^/]+$/i)
    const basePath = transformed ? transformed[1] : url.pathname
    const filename = basePath.split("/").pop()
    if (
      !basePath.startsWith(pathPrefix) ||
      !filename ||
      !/\.[a-z0-9]+$/i.test(filename) ||
      /\.svg$/i.test(filename)
    ) {
      return null
    }

    return { baseUrl: `${url.origin}${basePath}`, filename }
  } catch {
    return null
  }
}

const clampDim = (n) => Math.min(Math.max(Math.round(n), 1), MAX_DIMENSION)
const clamp01 = (n) => Math.min(1, Math.max(0, n))

export function buildTransformUrl(
  { baseUrl, filename },
  { width, height, crop, focalPoint, quality }
) {
  const params = [`w_${clampDim(width)}`, `h_${clampDim(height || width)}`]
  if (crop) {
    params.push(
      focalPoint
        ? `fp_${clamp01(focalPoint.x).toFixed(2)}_${clamp01(focalPoint.y).toFixed(2)}`
        : "al_c"
    )
  }
  params.push(`q_${quality}`, "usm_0.66_1.00_0.01", "enc_webp", "quality_auto")
  const outputName = /\.gif$/i.test(filename)
    ? filename
    : filename.replace(/\.[a-z0-9]+$/i, "") + ".webp"
  return `${baseUrl}/v1/${crop ? "fill" : "fit"}/${params.join(",")}/${outputName}`
}

export function buildSrcSet(parsed, options) {
  return DEVICE_PIXEL_RATIOS.map(
    (dpr) =>
      `${buildTransformUrl(parsed, {
        ...options,
        width: options.width * dpr,
        height: options.height ? options.height * dpr : undefined,
      })} ${dpr}x`
  ).join(", ")
}

export function getOriginalImageUrl(src, parsed) {
  return parsed?.baseUrl || src
}

export function nextImageLoadMode(mode) {
  return mode === IMAGE_LOAD_MODE.OPTIMIZED
    ? IMAGE_LOAD_MODE.ORIGINAL
    : IMAGE_LOAD_MODE.FALLBACK
}

```

---

## `src/components/ui/image.jsx`

```javascript
import * as React from "react"
import { useSize } from "@/hooks/use-size"
import { cn } from "@/lib/utils"
import {
  buildSrcSet,
  buildTransformUrl,
  DEFAULT_TRANSFORM_WIDTH,
  getOriginalImageUrl,
  IMAGE_LOAD_MODE,
  nextImageLoadMode,
  parseWixMediaUrl,
} from "./image-helpers"

const FALLBACK_IMAGE_URL =
  "https://static.wixstatic.com/media/12d367_4f26ccd17f8f4e3a8958306ea08c2332~mv2.png"

const ImageWrapper = React.forwardRef(({ aspectRatio, className, style, children }, ref) => (
  <span
    ref={ref}
    className={cn("inline-block relative", className)}
    style={{ aspectRatio, ...style }}
  >
    {children}
  </span>
))
ImageWrapper.displayName = "ImageWrapper"

const ResponsiveImage = React.forwardRef(
  ({ parsed, fittingType, focalPoint, quality, className, style, aspectRatio, onLoad, ...props }, parentRef) => {
    const wrapperRef = React.useRef(null)
    const imgRef = React.useRef(null)
    const size = useSize(wrapperRef)
    const [loaded, setLoaded] = React.useState(false)

    React.useImperativeHandle(parentRef, () => imgRef.current)

    // Reset the blur-up when the underlying image changes.
    React.useEffect(() => {
      setLoaded(false)
    }, [parsed.baseUrl])

    const crop = fittingType !== "fit"
    // `size` is null exactly once: the pre-measurement first render, which we
    // never let reach the network (see below — useSize measures before paint).
    // A *measured* zero (content-sized wrapper with no CSS dimensions) falls
    // back to a fixed transform width so the image itself can size the box.
    const options = size && {
      width: size.width || DEFAULT_TRANSFORM_WIDTH,
      height: size.height ? size.height : undefined,
      crop,
      focalPoint: crop ? focalPoint : undefined,
      quality,
    }

    // Both layers render only once the container is measured, so the first
    // URL the browser ever fetches is already the right size — never a
    // DEFAULT_TRANSFORM_WIDTH guess that gets replaced a frame later (a
    // wasted full-size download per image). useSize measures in
    // useLayoutEffect, so nothing is lost: measurement lands before the
    // first paint.
    return (
      <ImageWrapper ref={wrapperRef} aspectRatio={aspectRatio} className={className} style={style}>
        {/* Tiny blurred placeholder (a few hundred bytes) covering the main
            image's load time. Same crop shape and focal anchor as the main
            image — fp_ is relative to the crop box, so a square or centered
            placeholder would blur-preview a different region. */}
        {options && !loaded && (
          <img
            src={buildTransformUrl(parsed, {
              ...options,
              width: 20,
              height: options.height
                ? Math.max(1, Math.round((20 * options.height) / options.width))
                : undefined,
              quality: 20,
            })}
            alt=""
            aria-hidden="true"
            className="w-full h-full inset-0 absolute"
            style={{
              objectFit: fittingType === "fit" ? "contain" : "cover",
              filter: "blur(10px)",
              transform: "scale(1.1)",
            }}
          />
        )}
        {options && (
          <img
            ref={imgRef}
            src={buildTransformUrl(parsed, options)}
            srcSet={buildSrcSet(parsed, options)}
            loading="lazy"
            className={cn(
              "w-full h-full inset-0 absolute",
              fittingType === "fit" ? "object-contain" : "object-cover"
            )}
            onLoad={(e) => {
              setLoaded(true)
              onLoad?.(e)
            }}
            {...props}
          />
        )}
      </ImageWrapper>
    )
  }
)
ResponsiveImage.displayName = "ResponsiveImage"

/**
 * Image with built-in Wix Media Platform support: canonical public images on
 * media.base44.com and static.wixstatic.com/media are resized to the rendered
 * container per device pixel ratio and re-encoded to WebP; `fittingType="fill"`
 * crops server-side, optionally anchored at a focal point. Other URLs render
 * as a plain <img>. Failed transforms retry the original URL; only a broken
 * original swaps to the generic fallback image.
 */
const Image = React.forwardRef(
  (
    {
      src,
      fittingType = "fill",
      originWidth,
      originHeight,
      focalPointX,
      focalPointY,
      quality = 90,
      onError,
      ...props
    },
    ref
  ) => {
    const parsedSource = src && src !== FALLBACK_IMAGE_URL ? parseWixMediaUrl(src) : null
    const initialMode = parsedSource ? IMAGE_LOAD_MODE.OPTIMIZED : IMAGE_LOAD_MODE.ORIGINAL
    const [loadState, setLoadState] = React.useState({ src, mode: initialMode })
    const mode = loadState.src === src ? loadState.mode : initialMode

    React.useEffect(() => {
      setLoadState({ src, mode: initialMode })
    }, [src, initialMode])

    const handleError = (event) => {
      if (mode === IMAGE_LOAD_MODE.FALLBACK) return
      const nextMode = nextImageLoadMode(mode)
      setLoadState({ src, mode: nextMode })
      if (nextMode === IMAGE_LOAD_MODE.FALLBACK) onError?.(event)
    }

    const imageProps = {
      ...props,
      onError: handleError,
    }

    if (!src) {
      // Renders as a real <img> (not a <div>) — the visual editor's
      // click-to-edit toolbar keys its "Replace Image" action off the DOM
      // tag being `img`, so a placeholder div would be unrecoverable in the
      // editor. FALLBACK_IMAGE_URL doubles as the "no image chosen" graphic.
      return <img ref={ref} src={FALLBACK_IMAGE_URL} {...imageProps} data-empty-image />
    }

    // A failed transform retries the underlying original as a plain image.
    // Only a failure of that original advances to the generic fallback.
    const parsed = mode === IMAGE_LOAD_MODE.OPTIMIZED ? parsedSource : null

    if (!parsed) {
      const isErrorMode = mode === IMAGE_LOAD_MODE.FALLBACK
      const imageSrc = isErrorMode ? FALLBACK_IMAGE_URL : getOriginalImageUrl(src, parsedSource)
      return (
        <img ref={ref} src={imageSrc} {...imageProps} data-error-image={isErrorMode || undefined} />
      )
    }

    const focalPoint =
      typeof focalPointX === "number" && typeof focalPointY === "number"
        ? { x: focalPointX, y: focalPointY }
        : undefined
    // Origin dimensions are optional — when known they stabilize layout via
    // the wrapper's aspect-ratio before the image loads.
    const aspectRatio =
      originWidth && originHeight ? `${originWidth} / ${originHeight}` : undefined

    return (
      <ResponsiveImage
        ref={ref}
        parsed={parsed}
        fittingType={fittingType}
        focalPoint={focalPoint}
        quality={quality}
        aspectRatio={aspectRatio}
        {...imageProps}
      />
    )
  }
)
Image.displayName = "Image"

export { Image }

```

---

## `src/components/ui/input-otp.jsx`

```javascript
import * as React from "react"
import { OTPInput, OTPInputContext } from "input-otp"
import { Minus } from "lucide-react"

import { cn } from "@/lib/utils"

const InputOTP = React.forwardRef(({ className, containerClassName, ...props }, ref) => (
  <OTPInput
    ref={ref}
    containerClassName={cn("flex items-center gap-2 has-[:disabled]:opacity-50", containerClassName)}
    className={cn("disabled:cursor-not-allowed", className)}
    {...props} />
))
InputOTP.displayName = "InputOTP"

const InputOTPGroup = React.forwardRef(({ className, ...props }, ref) => (
  <div ref={ref} className={cn("flex items-center", className)} {...props} />
))
InputOTPGroup.displayName = "InputOTPGroup"

const InputOTPSlot = React.forwardRef(({ index, className, ...props }, ref) => {
  const inputOTPContext = React.useContext(OTPInputContext)
  const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index]

  return (
    (<div
      ref={ref}
      className={cn(
        "relative flex h-9 w-9 items-center justify-center border-y border-r border-input text-sm shadow-sm transition-all first:rounded-l-md first:border-l last:rounded-r-md",
        isActive && "z-10 ring-1 ring-ring",
        className
      )}
      {...props}>
      {char}
      {hasFakeCaret && (
        <div
          className="pointer-events-none absolute inset-0 flex items-center justify-center">
          <div className="h-4 w-px animate-caret-blink bg-foreground duration-1000" />
        </div>
      )}
    </div>)
  );
})
InputOTPSlot.displayName = "InputOTPSlot"

const InputOTPSeparator = React.forwardRef(({ ...props }, ref) => (
  <div ref={ref} role="separator" {...props}>
    <Minus />
  </div>
))
InputOTPSeparator.displayName = "InputOTPSeparator"

export { InputOTP, InputOTPGroup, InputOTPSlot, InputOTPSeparator }

```

---

## `src/components/ui/input.jsx`

```javascript
import * as React from "react"

import { cn } from "@/lib/utils"

const Input = React.forwardRef(({ className, type, ...props }, ref) => {
  return (
    (<input
      type={type}
      className={cn(
        "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-base shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
        className
      )}
      ref={ref}
      {...props} />)
  );
})
Input.displayName = "Input"

export { Input }

```

---

## `src/components/ui/label.jsx`

```javascript
import * as React from "react"
import * as LabelPrimitive from "@radix-ui/react-label"
import { cva } from "class-variance-authority";

import { cn } from "@/lib/utils"

const labelVariants = cva(
  "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
)

const Label = React.forwardRef(({ className, ...props }, ref) => (
  <LabelPrimitive.Root ref={ref} className={cn(labelVariants(), className)} {...props} />
))
Label.displayName = LabelPrimitive.Root.displayName

export { Label }

```

---

## `src/components/ui/menubar.jsx`

```javascript
"use client"

import * as React from "react"
import * as MenubarPrimitive from "@radix-ui/react-menubar"
import { Check, ChevronRight, Circle } from "lucide-react"

import { cn } from "@/lib/utils"

function MenubarMenu({
  ...props
}) {
  return <MenubarPrimitive.Menu {...props} />;
}

function MenubarGroup({
  ...props
}) {
  return <MenubarPrimitive.Group {...props} />;
}

function MenubarPortal({
  ...props
}) {
  return <MenubarPrimitive.Portal {...props} />;
}

function MenubarRadioGroup({
  ...props
}) {
  return <MenubarPrimitive.RadioGroup {...props} />;
}

function MenubarSub({
  ...props
}) {
  return <MenubarPrimitive.Sub data-slot="menubar-sub" {...props} />;
}

const Menubar = React.forwardRef(({ className, ...props }, ref) => (
  <MenubarPrimitive.Root
    ref={ref}
    className={cn(
      "flex h-9 items-center space-x-1 rounded-md border bg-background p-1 shadow-sm",
      className
    )}
    {...props} />
))
Menubar.displayName = MenubarPrimitive.Root.displayName

const MenubarTrigger = React.forwardRef(({ className, ...props }, ref) => (
  <MenubarPrimitive.Trigger
    ref={ref}
    className={cn(
      "flex cursor-default select-none items-center rounded-sm px-3 py-1 text-sm font-medium outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
      className
    )}
    {...props} />
))
MenubarTrigger.displayName = MenubarPrimitive.Trigger.displayName

const MenubarSubTrigger = React.forwardRef(({ className, inset, children, ...props }, ref) => (
  <MenubarPrimitive.SubTrigger
    ref={ref}
    className={cn(
      "flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[state=open]:bg-accent data-[state=open]:text-accent-foreground",
      inset && "pl-8",
      className
    )}
    {...props}>
    {children}
    <ChevronRight className="ml-auto h-4 w-4" />
  </MenubarPrimitive.SubTrigger>
))
MenubarSubTrigger.displayName = MenubarPrimitive.SubTrigger.displayName

const MenubarSubContent = React.forwardRef(({ className, ...props }, ref) => (
  <MenubarPrimitive.SubContent
    ref={ref}
    className={cn(
      "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
      className
    )}
    {...props} />
))
MenubarSubContent.displayName = MenubarPrimitive.SubContent.displayName

const MenubarContent = React.forwardRef((
  { className, align = "start", alignOffset = -4, sideOffset = 8, ...props },
  ref
) => (
  <MenubarPrimitive.Portal>
    <MenubarPrimitive.Content
      ref={ref}
      align={align}
      alignOffset={alignOffset}
      sideOffset={sideOffset}
      className={cn(
        "z-50 min-w-[12rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
        className
      )}
      {...props} />
  </MenubarPrimitive.Portal>
))
MenubarContent.displayName = MenubarPrimitive.Content.displayName

const MenubarItem = React.forwardRef(({ className, inset, ...props }, ref) => (
  <MenubarPrimitive.Item
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      inset && "pl-8",
      className
    )}
    {...props} />
))
MenubarItem.displayName = MenubarPrimitive.Item.displayName

const MenubarCheckboxItem = React.forwardRef(({ className, children, checked, ...props }, ref) => (
  <MenubarPrimitive.CheckboxItem
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    )}
    checked={checked}
    {...props}>
    <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
      <MenubarPrimitive.ItemIndicator>
        <Check className="h-4 w-4" />
      </MenubarPrimitive.ItemIndicator>
    </span>
    {children}
  </MenubarPrimitive.CheckboxItem>
))
MenubarCheckboxItem.displayName = MenubarPrimitive.CheckboxItem.displayName

const MenubarRadioItem = React.forwardRef(({ className, children, ...props }, ref) => (
  <MenubarPrimitive.RadioItem
    ref={ref}
    className={cn(
      "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    )}
    {...props}>
    <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
      <MenubarPrimitive.ItemIndicator>
        <Circle className="h-4 w-4 fill-current" />
      </MenubarPrimitive.ItemIndicator>
    </span>
    {children}
  </MenubarPrimitive.RadioItem>
))
MenubarRadioItem.displayName = MenubarPrimitive.RadioItem.displayName

const MenubarLabel = React.forwardRef(({ className, inset, ...props }, ref) => (
  <MenubarPrimitive.Label
    ref={ref}
    className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
    {...props} />
))
MenubarLabel.displayName = MenubarPrimitive.Label.displayName

const MenubarSeparator = React.forwardRef(({ className, ...props }, ref) => (
  <MenubarPrimitive.Separator
    ref={ref}
    className={cn("-mx-1 my-1 h-px bg-muted", className)}
    {...props} />
))
MenubarSeparator.displayName = MenubarPrimitive.Separator.displayName

const MenubarShortcut = ({
  className,
  ...props
}) => {
  return (
    (<span
      className={cn("ml-auto text-xs tracking-widest text-muted-foreground", className)}
      {...props} />)
  );
}
MenubarShortcut.displayname = "MenubarShortcut"

export {
  Menubar,
  MenubarMenu,
  MenubarTrigger,
  MenubarContent,
  MenubarItem,
  MenubarSeparator,
  MenubarLabel,
  MenubarCheckboxItem,
  MenubarRadioGroup,
  MenubarRadioItem,
  MenubarPortal,
  MenubarSubContent,
  MenubarSubTrigger,
  MenubarGroup,
  MenubarSub,
  MenubarShortcut,
}

```

---

## `src/components/ui/navigation-menu.jsx`

```javascript
import * as React from "react"
import * as NavigationMenuPrimitive from "@radix-ui/react-navigation-menu"
import { cva } from "class-variance-authority"
import { ChevronDown } from "lucide-react"

import { cn } from "@/lib/utils"

const NavigationMenu = React.forwardRef(({ className, children, ...props }, ref) => (
  <NavigationMenuPrimitive.Root
    ref={ref}
    className={cn(
      "relative z-10 flex max-w-max flex-1 items-center justify-center",
      className
    )}
    {...props}>
    {children}
    <NavigationMenuViewport />
  </NavigationMenuPrimitive.Root>
))
NavigationMenu.displayName = NavigationMenuPrimitive.Root.displayName

const NavigationMenuList = React.forwardRef(({ className, ...props }, ref) => (
  <NavigationMenuPrimitive.List
    ref={ref}
    className={cn(
      "group flex flex-1 list-none items-center justify-center space-x-1",
      className
    )}
    {...props} />
))
NavigationMenuList.displayName = NavigationMenuPrimitive.List.displayName

const NavigationMenuItem = NavigationMenuPrimitive.Item

const navigationMenuTriggerStyle = cva(
  "group inline-flex h-9 w-max items-center justify-center rounded-md bg-background px-4 py-2 text-sm font-medium transition-colors hover:bg-accent hover:text-accent-foreground focus:bg-accent focus:text-accent-foreground focus:outline-none disabled:pointer-events-none disabled:opacity-50 data-[active]:bg-accent/50 data-[state=open]:bg-accent/50"
)

const NavigationMenuTrigger = React.forwardRef(({ className, children, ...props }, ref) => (
  <NavigationMenuPrimitive.Trigger
    ref={ref}
    className={cn(navigationMenuTriggerStyle(), "group", className)}
    {...props}>
    {children}{" "}
    <ChevronDown
      className="relative top-[1px] ml-1 h-3 w-3 transition duration-300 group-data-[state=open]:rotate-180"
      aria-hidden="true" />
  </NavigationMenuPrimitive.Trigger>
))
NavigationMenuTrigger.displayName = NavigationMenuPrimitive.Trigger.displayName

const NavigationMenuContent = React.forwardRef(({ className, ...props }, ref) => (
  <NavigationMenuPrimitive.Content
    ref={ref}
    className={cn(
      "left-0 top-0 w-full data-[motion^=from-]:animate-in data-[motion^=to-]:animate-out data-[motion^=from-]:fade-in data-[motion^=to-]:fade-out data-[motion=from-end]:slide-in-from-right-52 data-[motion=from-start]:slide-in-from-left-52 data-[motion=to-end]:slide-out-to-right-52 data-[motion=to-start]:slide-out-to-left-52 md:absolute md:w-auto ",
      className
    )}
    {...props} />
))
NavigationMenuContent.displayName = NavigationMenuPrimitive.Content.displayName

const NavigationMenuLink = NavigationMenuPrimitive.Link

const NavigationMenuViewport = React.forwardRef(({ className, ...props }, ref) => (
  <div className={cn("absolute left-0 top-full flex justify-center")}>
    <NavigationMenuPrimitive.Viewport
      className={cn(
        "origin-top-center relative mt-1.5 h-[var(--radix-navigation-menu-viewport-height)] w-full overflow-hidden rounded-md border bg-popover text-popover-foreground shadow data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-90 md:w-[var(--radix-navigation-menu-viewport-width)]",
        className
      )}
      ref={ref}
      {...props} />
  </div>
))
NavigationMenuViewport.displayName =
  NavigationMenuPrimitive.Viewport.displayName

const NavigationMenuIndicator = React.forwardRef(({ className, ...props }, ref) => (
  <NavigationMenuPrimitive.Indicator
    ref={ref}
    className={cn(
      "top-full z-[1] flex h-1.5 items-end justify-center overflow-hidden data-[state=visible]:animate-in data-[state=hidden]:animate-out data-[state=hidden]:fade-out data-[state=visible]:fade-in",
      className
    )}
    {...props}>
    <div
      className="relative top-[60%] h-2 w-2 rotate-45 rounded-tl-sm bg-border shadow-md" />
  </NavigationMenuPrimitive.Indicator>
))
NavigationMenuIndicator.displayName =
  NavigationMenuPrimitive.Indicator.displayName

export {
  navigationMenuTriggerStyle,
  NavigationMenu,
  NavigationMenuList,
  NavigationMenuItem,
  NavigationMenuContent,
  NavigationMenuTrigger,
  NavigationMenuLink,
  NavigationMenuIndicator,
  NavigationMenuViewport,
}

```

---

## `src/components/ui/pagination.jsx`

```javascript
import * as React from "react"
import { ChevronLeft, ChevronRight, MoreHorizontal } from "lucide-react"

import { cn } from "@/lib/utils"
import { buttonVariants } from "@/components/ui/button";

const Pagination = ({
  className,
  ...props
}) => (
  <nav
    role="navigation"
    aria-label="pagination"
    className={cn("mx-auto flex w-full justify-center", className)}
    {...props} />
)
Pagination.displayName = "Pagination"

const PaginationContent = React.forwardRef(({ className, ...props }, ref) => (
  <ul
    ref={ref}
    className={cn("flex flex-row items-center gap-1", className)}
    {...props} />
))
PaginationContent.displayName = "PaginationContent"

const PaginationItem = React.forwardRef(({ className, ...props }, ref) => (
  <li ref={ref} className={cn("", className)} {...props} />
))
PaginationItem.displayName = "PaginationItem"

const PaginationLink = ({
  className,
  isActive,
  size = "icon",
  ...props
}) => (
  <a
    aria-current={isActive ? "page" : undefined}
    className={cn(buttonVariants({
      variant: isActive ? "outline" : "ghost",
      size,
    }), className)}
    {...props} />
)
PaginationLink.displayName = "PaginationLink"

const PaginationPrevious = ({
  className,
  ...props
}) => (
  <PaginationLink
    aria-label="Go to previous page"
    size="default"
    className={cn("gap-1 pl-2.5", className)}
    {...props}>
    <ChevronLeft className="h-4 w-4" />
    <span>Previous</span>
  </PaginationLink>
)
PaginationPrevious.displayName = "PaginationPrevious"

const PaginationNext = ({
  className,
  ...props
}) => (
  <PaginationLink
    aria-label="Go to next page"
    size="default"
    className={cn("gap-1 pr-2.5", className)}
    {...props}>
    <span>Next</span>
    <ChevronRight className="h-4 w-4" />
  </PaginationLink>
)
PaginationNext.displayName = "PaginationNext"

const PaginationEllipsis = ({
  className,
  ...props
}) => (
  <span
    aria-hidden
    className={cn("flex h-9 w-9 items-center justify-center", className)}
    {...props}>
    <MoreHorizontal className="h-4 w-4" />
    <span className="sr-only">More pages</span>
  </span>
)
PaginationEllipsis.displayName = "PaginationEllipsis"

export {
  Pagination,
  PaginationContent,
  PaginationLink,
  PaginationItem,
  PaginationPrevious,
  PaginationNext,
  PaginationEllipsis,
}

```

---

## `src/components/ui/popover.jsx`

```javascript
import * as React from "react"
import * as PopoverPrimitive from "@radix-ui/react-popover"

import { cn } from "@/lib/utils"

const Popover = PopoverPrimitive.Root

const PopoverTrigger = PopoverPrimitive.Trigger

const PopoverAnchor = PopoverPrimitive.Anchor

const PopoverContent = React.forwardRef(({ className, align = "center", sideOffset = 4, ...props }, ref) => (
  <PopoverPrimitive.Portal>
    <PopoverPrimitive.Content
      ref={ref}
      align={align}
      sideOffset={sideOffset}
      className={cn(
        "z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
        className
      )}
      {...props} />
  </PopoverPrimitive.Portal>
))
PopoverContent.displayName = PopoverPrimitive.Content.displayName

export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor }

```

---

## `src/components/ui/progress.jsx`

```javascript
"use client"

import * as React from "react"
import * as ProgressPrimitive from "@radix-ui/react-progress"

import { cn } from "@/lib/utils"

const Progress = React.forwardRef(({ className, value, ...props }, ref) => (
  <ProgressPrimitive.Root
    ref={ref}
    className={cn(
      "relative h-2 w-full overflow-hidden rounded-full bg-primary/20",
      className
    )}
    {...props}>
    <ProgressPrimitive.Indicator
      className="h-full w-full flex-1 bg-primary transition-all"
      style={{ transform: `translateX(-${100 - (value || 0)}%)` }} />
  </ProgressPrimitive.Root>
))
Progress.displayName = ProgressPrimitive.Root.displayName

export { Progress }

```

---

## `src/components/ui/radio-group.jsx`

```javascript
import * as React from "react"
import * as RadioGroupPrimitive from "@radix-ui/react-radio-group"
import { Circle } from "lucide-react"

import { cn } from "@/lib/utils"

const RadioGroup = React.forwardRef(({ className, ...props }, ref) => {
  return (<RadioGroupPrimitive.Root className={cn("grid gap-2", className)} {...props} ref={ref} />);
})
RadioGroup.displayName = RadioGroupPrimitive.Root.displayName

const RadioGroupItem = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<RadioGroupPrimitive.Item
      ref={ref}
      className={cn(
        "aspect-square h-4 w-4 rounded-full border border-primary text-primary shadow focus:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
        className
      )}
      {...props}>
      <RadioGroupPrimitive.Indicator className="flex items-center justify-center">
        <Circle className="h-3.5 w-3.5 fill-primary" />
      </RadioGroupPrimitive.Indicator>
    </RadioGroupPrimitive.Item>)
  );
})
RadioGroupItem.displayName = RadioGroupPrimitive.Item.displayName

export { RadioGroup, RadioGroupItem }

```

---

## `src/components/ui/resizable.jsx`

```javascript
"use client"

import { GripVertical } from "lucide-react"
import * as ResizablePrimitive from "react-resizable-panels"

import { cn } from "@/lib/utils"

const ResizablePanelGroup = ({
  className,
  ...props
}) => (
  <ResizablePrimitive.PanelGroup
    className={cn(
      "flex h-full w-full data-[panel-group-direction=vertical]:flex-col",
      className
    )}
    {...props} />
)

const ResizablePanel = ResizablePrimitive.Panel

const ResizableHandle = ({
  withHandle,
  className,
  ...props
}) => (
  <ResizablePrimitive.PanelResizeHandle
    className={cn(
      "relative flex w-px items-center justify-center bg-border after:absolute after:inset-y-0 after:left-1/2 after:w-1 after:-translate-x-1/2 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring focus-visible:ring-offset-1 data-[panel-group-direction=vertical]:h-px data-[panel-group-direction=vertical]:w-full data-[panel-group-direction=vertical]:after:left-0 data-[panel-group-direction=vertical]:after:h-1 data-[panel-group-direction=vertical]:after:w-full data-[panel-group-direction=vertical]:after:-translate-y-1/2 data-[panel-group-direction=vertical]:after:translate-x-0 [&[data-panel-group-direction=vertical]>div]:rotate-90",
      className
    )}
    {...props}>
    {withHandle && (
      <div
        className="z-10 flex h-4 w-3 items-center justify-center rounded-sm border bg-border">
        <GripVertical className="h-2.5 w-2.5" />
      </div>
    )}
  </ResizablePrimitive.PanelResizeHandle>
)

export { ResizablePanelGroup, ResizablePanel, ResizableHandle }

```

---

## `src/components/ui/scroll-area.jsx`

```javascript
import * as React from "react"
import * as ScrollAreaPrimitive from "@radix-ui/react-scroll-area"

import { cn } from "@/lib/utils"

const ScrollArea = React.forwardRef(({ className, children, ...props }, ref) => (
  <ScrollAreaPrimitive.Root
    ref={ref}
    className={cn("relative overflow-hidden", className)}
    {...props}>
    <ScrollAreaPrimitive.Viewport className="h-full w-full rounded-[inherit]">
      {children}
    </ScrollAreaPrimitive.Viewport>
    <ScrollBar />
    <ScrollAreaPrimitive.Corner />
  </ScrollAreaPrimitive.Root>
))
ScrollArea.displayName = ScrollAreaPrimitive.Root.displayName

const ScrollBar = React.forwardRef(({ className, orientation = "vertical", ...props }, ref) => (
  <ScrollAreaPrimitive.ScrollAreaScrollbar
    ref={ref}
    orientation={orientation}
    className={cn(
      "flex touch-none select-none transition-colors",
      orientation === "vertical" &&
        "h-full w-2.5 border-l border-l-transparent p-[1px]",
      orientation === "horizontal" &&
        "h-2.5 flex-col border-t border-t-transparent p-[1px]",
      className
    )}
    {...props}>
    <ScrollAreaPrimitive.ScrollAreaThumb className="relative flex-1 rounded-full bg-border" />
  </ScrollAreaPrimitive.ScrollAreaScrollbar>
))
ScrollBar.displayName = ScrollAreaPrimitive.ScrollAreaScrollbar.displayName

export { ScrollArea, ScrollBar }

```

---

## `src/components/ui/select.jsx`

```javascript
"use client"

import * as React from "react"
import * as SelectPrimitive from "@radix-ui/react-select"
import { Check, ChevronDown, ChevronUp } from "lucide-react"

import { cn } from "@/lib/utils"

const Select = SelectPrimitive.Root

const SelectGroup = SelectPrimitive.Group

const SelectValue = SelectPrimitive.Value

const SelectTrigger = React.forwardRef(({ className, children, ...props }, ref) => (
  <SelectPrimitive.Trigger
    ref={ref}
    className={cn(
      "flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background data-[placeholder]:text-muted-foreground focus:outline-none focus:ring-1 focus:ring-ring disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
      className
    )}
    {...props}>
    {children}
    <SelectPrimitive.Icon asChild>
      <ChevronDown className="h-4 w-4 opacity-50" />
    </SelectPrimitive.Icon>
  </SelectPrimitive.Trigger>
))
SelectTrigger.displayName = SelectPrimitive.Trigger.displayName

const SelectScrollUpButton = React.forwardRef(({ className, ...props }, ref) => (
  <SelectPrimitive.ScrollUpButton
    ref={ref}
    className={cn("flex cursor-default items-center justify-center py-1", className)}
    {...props}>
    <ChevronUp className="h-4 w-4" />
  </SelectPrimitive.ScrollUpButton>
))
SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName

const SelectScrollDownButton = React.forwardRef(({ className, ...props }, ref) => (
  <SelectPrimitive.ScrollDownButton
    ref={ref}
    className={cn("flex cursor-default items-center justify-center py-1", className)}
    {...props}>
    <ChevronDown className="h-4 w-4" />
  </SelectPrimitive.ScrollDownButton>
))
SelectScrollDownButton.displayName =
  SelectPrimitive.ScrollDownButton.displayName

const SelectContent = React.forwardRef(({ className, children, position = "popper", ...props }, ref) => (
  <SelectPrimitive.Portal>
    <SelectPrimitive.Content
      ref={ref}
      className={cn(
        "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
        position === "popper" &&
          "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
        className
      )}
      position={position}
      {...props}>
      <SelectScrollUpButton />
      <SelectPrimitive.Viewport
        className={cn("p-1", position === "popper" &&
          "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]")}>
        {children}
      </SelectPrimitive.Viewport>
      <SelectScrollDownButton />
    </SelectPrimitive.Content>
  </SelectPrimitive.Portal>
))
SelectContent.displayName = SelectPrimitive.Content.displayName

const SelectLabel = React.forwardRef(({ className, ...props }, ref) => (
  <SelectPrimitive.Label
    ref={ref}
    className={cn("px-2 py-1.5 text-sm font-semibold", className)}
    {...props} />
))
SelectLabel.displayName = SelectPrimitive.Label.displayName

const SelectItem = React.forwardRef(({ className, children, ...props }, ref) => (
  <SelectPrimitive.Item
    ref={ref}
    className={cn(
      "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
      className
    )}
    {...props}>
    <span className="absolute right-2 flex h-3.5 w-3.5 items-center justify-center">
      <SelectPrimitive.ItemIndicator>
        <Check className="h-4 w-4" />
      </SelectPrimitive.ItemIndicator>
    </span>
    <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
  </SelectPrimitive.Item>
))
SelectItem.displayName = SelectPrimitive.Item.displayName

const SelectSeparator = React.forwardRef(({ className, ...props }, ref) => (
  <SelectPrimitive.Separator
    ref={ref}
    className={cn("-mx-1 my-1 h-px bg-muted", className)}
    {...props} />
))
SelectSeparator.displayName = SelectPrimitive.Separator.displayName

export {
  Select,
  SelectGroup,
  SelectValue,
  SelectTrigger,
  SelectContent,
  SelectLabel,
  SelectItem,
  SelectSeparator,
  SelectScrollUpButton,
  SelectScrollDownButton,
}

```

---

## `src/components/ui/separator.jsx`

```javascript
import * as React from "react"
import * as SeparatorPrimitive from "@radix-ui/react-separator"

import { cn } from "@/lib/utils"

const Separator = React.forwardRef((
  { className, orientation = "horizontal", decorative = true, ...props },
  ref
) => (
  <SeparatorPrimitive.Root
    ref={ref}
    decorative={decorative}
    orientation={orientation}
    className={cn(
      "shrink-0 bg-border",
      orientation === "horizontal" ? "h-[1px] w-full" : "h-full w-[1px]",
      className
    )}
    {...props} />
))
Separator.displayName = SeparatorPrimitive.Root.displayName

export { Separator }

```

---

## `src/components/ui/sheet.jsx`

```javascript
"use client";
import * as React from "react"
import * as SheetPrimitive from "@radix-ui/react-dialog"
import { cva } from "class-variance-authority";
import { X } from "lucide-react"

import { cn } from "@/lib/utils"

const Sheet = SheetPrimitive.Root

const SheetTrigger = SheetPrimitive.Trigger

const SheetClose = SheetPrimitive.Close

const SheetPortal = SheetPrimitive.Portal

const SheetOverlay = React.forwardRef(({ className, ...props }, ref) => (
  <SheetPrimitive.Overlay
    className={cn(
      "fixed inset-0 z-50 bg-black/80  data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
      className
    )}
    {...props}
    ref={ref} />
))
SheetOverlay.displayName = SheetPrimitive.Overlay.displayName

const sheetVariants = cva(
  "fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=closed]:duration-300 data-[state=open]:duration-500 data-[state=open]:animate-in data-[state=closed]:animate-out",
  {
    variants: {
      side: {
        top: "inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",
        bottom:
          "inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",
        left: "inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",
        right:
          "inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm",
      },
    },
    defaultVariants: {
      side: "right",
    },
  }
)

const SheetContent = React.forwardRef(({ side = "right", className, children, ...props }, ref) => (
  <SheetPortal>
    <SheetOverlay />
    <SheetPrimitive.Content ref={ref} className={cn(sheetVariants({ side }), className)} {...props}>
      <SheetPrimitive.Close
        className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary">
        <X className="h-4 w-4" />
        <span className="sr-only">Close</span>
      </SheetPrimitive.Close>
      {children}
    </SheetPrimitive.Content>
  </SheetPortal>
))
SheetContent.displayName = SheetPrimitive.Content.displayName

const SheetHeader = ({
  className,
  ...props
}) => (
  <div
    className={cn("flex flex-col space-y-2 text-center sm:text-left", className)}
    {...props} />
)
SheetHeader.displayName = "SheetHeader"

const SheetFooter = ({
  className,
  ...props
}) => (
  <div
    className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
    {...props} />
)
SheetFooter.displayName = "SheetFooter"

const SheetTitle = React.forwardRef(({ className, ...props }, ref) => (
  <SheetPrimitive.Title
    ref={ref}
    className={cn("text-lg font-semibold text-foreground", className)}
    {...props} />
))
SheetTitle.displayName = SheetPrimitive.Title.displayName

const SheetDescription = React.forwardRef(({ className, ...props }, ref) => (
  <SheetPrimitive.Description
    ref={ref}
    className={cn("text-sm text-muted-foreground", className)}
    {...props} />
))
SheetDescription.displayName = SheetPrimitive.Description.displayName

export {
  Sheet,
  SheetPortal,
  SheetOverlay,
  SheetTrigger,
  SheetClose,
  SheetContent,
  SheetHeader,
  SheetFooter,
  SheetTitle,
  SheetDescription,
}

```

---

## `src/components/ui/sidebar.jsx`

```javascript
import * as React from "react"
import { Slot } from "@radix-ui/react-slot"
import { cva } from "class-variance-authority";
import { PanelLeft } from "lucide-react"

import { useIsMobile } from "@/hooks/use-mobile"
import { cn } from "@/lib/utils"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Separator } from "@/components/ui/separator"
import { Sheet, SheetContent } from "@/components/ui/sheet"
import { Skeleton } from "@/components/ui/skeleton"
import {
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from "@/components/ui/tooltip"

const SIDEBAR_COOKIE_NAME = "sidebar_state"
const SIDEBAR_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
const SIDEBAR_WIDTH = "16rem"
const SIDEBAR_WIDTH_MOBILE = "18rem"
const SIDEBAR_WIDTH_ICON = "3rem"
const SIDEBAR_KEYBOARD_SHORTCUT = "b"

const SidebarContext = React.createContext(null)

function useSidebar() {
  const context = React.useContext(SidebarContext)
  if (!context) {
    throw new Error("useSidebar must be used within a SidebarProvider.")
  }

  return context
}

const SidebarProvider = React.forwardRef((
  {
    defaultOpen = true,
    open: openProp,
    onOpenChange: setOpenProp,
    className,
    style,
    children,
    ...props
  },
  ref
) => {
  const isMobile = useIsMobile()
  const [openMobile, setOpenMobile] = React.useState(false)

  // This is the internal state of the sidebar.
  // We use openProp and setOpenProp for control from outside the component.
  const [_open, _setOpen] = React.useState(defaultOpen)
  const open = openProp ?? _open
  const setOpen = React.useCallback((value) => {
    const openState = typeof value === "function" ? value(open) : value
    if (setOpenProp) {
      setOpenProp(openState)
    } else {
      _setOpen(openState)
    }

    // This sets the cookie to keep the sidebar state.
    document.cookie = `${SIDEBAR_COOKIE_NAME}=${openState}; path=/; max-age=${SIDEBAR_COOKIE_MAX_AGE}`
  }, [setOpenProp, open])

  // Helper to toggle the sidebar.
  const toggleSidebar = React.useCallback(() => {
    return isMobile
      ? setOpenMobile((open) => !open)
      : setOpen((open) => !open);
  }, [isMobile, setOpen, setOpenMobile])

  // Adds a keyboard shortcut to toggle the sidebar.
  React.useEffect(() => {
    const handleKeyDown = (event) => {
      if (
        event.key === SIDEBAR_KEYBOARD_SHORTCUT &&
        (event.metaKey || event.ctrlKey)
      ) {
        event.preventDefault()
        toggleSidebar()
      }
    }

    window.addEventListener("keydown", handleKeyDown)
    return () => window.removeEventListener("keydown", handleKeyDown);
  }, [toggleSidebar])

  // We add a state so that we can do data-state="expanded" or "collapsed".
  // This makes it easier to style the sidebar with Tailwind classes.
  const state = open ? "expanded" : "collapsed"

  const contextValue = React.useMemo(() => ({
    state,
    open,
    setOpen,
    isMobile,
    openMobile,
    setOpenMobile,
    toggleSidebar,
  }), [state, open, setOpen, isMobile, openMobile, setOpenMobile, toggleSidebar])

  return (
    (<SidebarContext.Provider value={contextValue}>
      <TooltipProvider delayDuration={0}>
        <div
          style={
            {
              "--sidebar-width": SIDEBAR_WIDTH,
              "--sidebar-width-icon": SIDEBAR_WIDTH_ICON,
              ...style
            }
          }
          className={cn(
            "group/sidebar-wrapper flex min-h-svh w-full has-[[data-variant=inset]]:bg-sidebar",
            className
          )}
          ref={ref}
          {...props}>
          {children}
        </div>
      </TooltipProvider>
    </SidebarContext.Provider>)
  );
})
SidebarProvider.displayName = "SidebarProvider"

const Sidebar = React.forwardRef((
  {
    side = "left",
    variant = "sidebar",
    collapsible = "offcanvas",
    className,
    children,
    ...props
  },
  ref
) => {
  const { isMobile, state, openMobile, setOpenMobile } = useSidebar()

  if (collapsible === "none") {
    return (
      (<div
        className={cn(
          "flex h-full w-[--sidebar-width] flex-col bg-sidebar text-sidebar-foreground",
          className
        )}
        ref={ref}
        {...props}>
        {children}
      </div>)
    );
  }

  if (isMobile) {
    return (
      (<Sheet open={openMobile} onOpenChange={setOpenMobile} {...props}>
        <SheetContent
          data-sidebar="sidebar"
          data-mobile="true"
          className="w-[--sidebar-width] bg-sidebar p-0 text-sidebar-foreground [&>button]:hidden"
          style={
            {
              "--sidebar-width": SIDEBAR_WIDTH_MOBILE
            }
          }
          side={side}>
          <div className="flex h-full w-full flex-col">{children}</div>
        </SheetContent>
      </Sheet>)
    );
  }

  return (
    (<div
      ref={ref}
      className="group peer hidden text-sidebar-foreground md:block"
      data-state={state}
      data-collapsible={state === "collapsed" ? collapsible : ""}
      data-variant={variant}
      data-side={side}>
      {/* This is what handles the sidebar gap on desktop */}
      <div
        className={cn(
          "relative h-svh w-[--sidebar-width] bg-transparent transition-[width] duration-200 ease-linear",
          "group-data-[collapsible=offcanvas]:w-0",
          "group-data-[side=right]:rotate-180",
          variant === "floating" || variant === "inset"
            ? "group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4))]"
            : "group-data-[collapsible=icon]:w-[--sidebar-width-icon]"
        )} />
      <div
        className={cn(
          "fixed inset-y-0 z-10 hidden h-svh w-[--sidebar-width] transition-[left,right,width] duration-200 ease-linear md:flex",
          side === "left"
            ? "left-0 group-data-[collapsible=offcanvas]:left-[calc(var(--sidebar-width)*-1)]"
            : "right-0 group-data-[collapsible=offcanvas]:right-[calc(var(--sidebar-width)*-1)]",
          // Adjust the padding for floating and inset variants.
          variant === "floating" || variant === "inset"
            ? "p-2 group-data-[collapsible=icon]:w-[calc(var(--sidebar-width-icon)_+_theme(spacing.4)_+2px)]"
            : "group-data-[collapsible=icon]:w-[--sidebar-width-icon] group-data-[side=left]:border-r group-data-[side=right]:border-l",
          className
        )}
        {...props}>
        <div
          data-sidebar="sidebar"
          className="flex h-full w-full flex-col bg-sidebar group-data-[variant=floating]:rounded-lg group-data-[variant=floating]:border group-data-[variant=floating]:border-sidebar-border group-data-[variant=floating]:shadow">
          {children}
        </div>
      </div>
    </div>)
  );
})
Sidebar.displayName = "Sidebar"

const SidebarTrigger = React.forwardRef(({ className, onClick, asChild = false, ...props }, ref) => {
  const { toggleSidebar } = useSidebar()

  return (
    (<Button
      ref={ref}
      data-sidebar="trigger"
      variant="ghost"
      size="icon"
      className={cn("h-7 w-7", className)}
      onClick={(event) => {
        onClick?.(event)
        toggleSidebar()
      }}
      asChild={asChild}
      {...props}>
      {asChild ? (
        <PanelLeft />
      ) : (
        <>
          <PanelLeft />
          <span className="sr-only">Toggle Sidebar</span>
        </>
      )}
    </Button>)
  );
})
SidebarTrigger.displayName = "SidebarTrigger"

const SidebarRail = React.forwardRef(({ className, ...props }, ref) => {
  const { toggleSidebar } = useSidebar()

  return (
    (<button
      ref={ref}
      data-sidebar="rail"
      aria-label="Toggle Sidebar"
      tabIndex={-1}
      onClick={toggleSidebar}
      title="Toggle Sidebar"
      className={cn(
        "absolute inset-y-0 z-20 hidden w-4 -translate-x-1/2 transition-all ease-linear after:absolute after:inset-y-0 after:left-1/2 after:w-[2px] hover:after:bg-sidebar-border group-data-[side=left]:-right-4 group-data-[side=right]:left-0 sm:flex",
        "[[data-side=left]_&]:cursor-w-resize [[data-side=right]_&]:cursor-e-resize",
        "[[data-side=left][data-state=collapsed]_&]:cursor-e-resize [[data-side=right][data-state=collapsed]_&]:cursor-w-resize",
        "group-data-[collapsible=offcanvas]:translate-x-0 group-data-[collapsible=offcanvas]:after:left-full group-data-[collapsible=offcanvas]:hover:bg-sidebar",
        "[[data-side=left][data-collapsible=offcanvas]_&]:-right-2",
        "[[data-side=right][data-collapsible=offcanvas]_&]:-left-2",
        className
      )}
      {...props} />)
  );
})
SidebarRail.displayName = "SidebarRail"

const SidebarInset = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<main
      ref={ref}
      className={cn(
        "relative flex min-h-svh flex-1 flex-col bg-background",
        "peer-data-[variant=inset]:min-h-[calc(100svh-theme(spacing.4))] md:peer-data-[variant=inset]:m-2 md:peer-data-[state=collapsed]:peer-data-[variant=inset]:ml-2 md:peer-data-[variant=inset]:ml-0 md:peer-data-[variant=inset]:rounded-xl md:peer-data-[variant=inset]:shadow",
        className
      )}
      {...props} />)
  );
})
SidebarInset.displayName = "SidebarInset"

const SidebarInput = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<Input
      ref={ref}
      data-sidebar="input"
      className={cn(
        "h-8 w-full bg-background shadow-none focus-visible:ring-2 focus-visible:ring-sidebar-ring",
        className
      )}
      {...props} />)
  );
})
SidebarInput.displayName = "SidebarInput"

const SidebarHeader = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<div
      ref={ref}
      data-sidebar="header"
      className={cn("flex flex-col gap-2 p-2", className)}
      {...props} />)
  );
})
SidebarHeader.displayName = "SidebarHeader"

const SidebarFooter = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<div
      ref={ref}
      data-sidebar="footer"
      className={cn("flex flex-col gap-2 p-2", className)}
      {...props} />)
  );
})
SidebarFooter.displayName = "SidebarFooter"

const SidebarSeparator = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<Separator
      ref={ref}
      data-sidebar="separator"
      className={cn("mx-2 w-auto bg-sidebar-border", className)}
      {...props} />)
  );
})
SidebarSeparator.displayName = "SidebarSeparator"

const SidebarContent = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<div
      ref={ref}
      data-sidebar="content"
      className={cn(
        "flex min-h-0 flex-1 flex-col gap-2 overflow-auto group-data-[collapsible=icon]:overflow-hidden",
        className
      )}
      {...props} />)
  );
})
SidebarContent.displayName = "SidebarContent"

const SidebarGroup = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<div
      ref={ref}
      data-sidebar="group"
      className={cn("relative flex w-full min-w-0 flex-col p-2", className)}
      {...props} />)
  );
})
SidebarGroup.displayName = "SidebarGroup"

const SidebarGroupLabel = React.forwardRef(({ className, asChild = false, ...props }, ref) => {
  const Comp = asChild ? Slot : "div"

  return (
    (<Comp
      ref={ref}
      data-sidebar="group-label"
      className={cn(
        "flex h-8 shrink-0 items-center rounded-md px-2 text-xs font-medium text-sidebar-foreground/70 outline-none ring-sidebar-ring transition-[margin,opacity] duration-200 ease-linear focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
        "group-data-[collapsible=icon]:-mt-8 group-data-[collapsible=icon]:opacity-0",
        className
      )}
      {...props} />)
  );
})
SidebarGroupLabel.displayName = "SidebarGroupLabel"

const SidebarGroupAction = React.forwardRef(({ className, asChild = false, ...props }, ref) => {
  const Comp = asChild ? Slot : "button"

  return (
    (<Comp
      ref={ref}
      data-sidebar="group-action"
      className={cn(
        "absolute right-3 top-3.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 [&>svg]:size-4 [&>svg]:shrink-0",
        // Increases the hit area of the button on mobile.
        "after:absolute after:-inset-2 after:md:hidden",
        "group-data-[collapsible=icon]:hidden",
        className
      )}
      {...props} />)
  );
})
SidebarGroupAction.displayName = "SidebarGroupAction"

const SidebarGroupContent = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    data-sidebar="group-content"
    className={cn("w-full text-sm", className)}
    {...props} />
))
SidebarGroupContent.displayName = "SidebarGroupContent"

const SidebarMenu = React.forwardRef(({ className, ...props }, ref) => (
  <ul
    ref={ref}
    data-sidebar="menu"
    className={cn("flex w-full min-w-0 flex-col gap-1", className)}
    {...props} />
))
SidebarMenu.displayName = "SidebarMenu"

const SidebarMenuItem = React.forwardRef(({ className, ...props }, ref) => (
  <li
    ref={ref}
    data-sidebar="menu-item"
    className={cn("group/menu-item relative", className)}
    {...props} />
))
SidebarMenuItem.displayName = "SidebarMenuItem"

const sidebarMenuButtonVariants = cva(
  "peer/menu-button flex w-full items-center gap-2 overflow-hidden rounded-md p-2 text-left text-sm outline-none ring-sidebar-ring transition-[width,height,padding] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 group-has-[[data-sidebar=menu-action]]/menu-item:pr-8 aria-disabled:pointer-events-none aria-disabled:opacity-50 data-[active=true]:bg-sidebar-accent data-[active=true]:font-medium data-[active=true]:text-sidebar-accent-foreground data-[state=open]:hover:bg-sidebar-accent data-[state=open]:hover:text-sidebar-accent-foreground group-data-[collapsible=icon]:!size-8 group-data-[collapsible=icon]:!p-2 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0",
  {
    variants: {
      variant: {
        default: "hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",
        outline:
          "bg-background shadow-[0_0_0_1px_hsl(var(--sidebar-border))] hover:bg-sidebar-accent hover:text-sidebar-accent-foreground hover:shadow-[0_0_0_1px_hsl(var(--sidebar-accent))]",
      },
      size: {
        default: "h-8 text-sm",
        sm: "h-7 text-xs",
        lg: "h-12 text-sm group-data-[collapsible=icon]:!p-0",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

const SidebarMenuButton = React.forwardRef((
  {
    asChild = false,
    isActive = false,
    variant = "default",
    size = "default",
    tooltip,
    className,
    ...props
  },
  ref
) => {
  const Comp = asChild ? Slot : "button"
  const { isMobile, state } = useSidebar()

  const button = (
    <Comp
      ref={ref}
      data-sidebar="menu-button"
      data-size={size}
      data-active={isActive}
      className={cn(sidebarMenuButtonVariants({ variant, size }), className)}
      {...props} />
  )

  if (!tooltip) {
    return button
  }

  if (typeof tooltip === "string") {
    tooltip = {
      children: tooltip,
    }
  }

  return (
    (<Tooltip>
      <TooltipTrigger asChild>{button}</TooltipTrigger>
      <TooltipContent
        side="right"
        align="center"
        hidden={state !== "collapsed" || isMobile}
        {...tooltip} />
    </Tooltip>)
  );
})
SidebarMenuButton.displayName = "SidebarMenuButton"

const SidebarMenuAction = React.forwardRef(({ className, asChild = false, showOnHover = false, ...props }, ref) => {
  const Comp = asChild ? Slot : "button"

  return (
    (<Comp
      ref={ref}
      data-sidebar="menu-action"
      className={cn(
        "absolute right-1 top-1.5 flex aspect-square w-5 items-center justify-center rounded-md p-0 text-sidebar-foreground outline-none ring-sidebar-ring transition-transform hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 peer-hover/menu-button:text-sidebar-accent-foreground [&>svg]:size-4 [&>svg]:shrink-0",
        // Increases the hit area of the button on mobile.
        "after:absolute after:-inset-2 after:md:hidden",
        "peer-data-[size=sm]/menu-button:top-1",
        "peer-data-[size=default]/menu-button:top-1.5",
        "peer-data-[size=lg]/menu-button:top-2.5",
        "group-data-[collapsible=icon]:hidden",
        showOnHover &&
        "group-focus-within/menu-item:opacity-100 group-hover/menu-item:opacity-100 data-[state=open]:opacity-100 peer-data-[active=true]/menu-button:text-sidebar-accent-foreground md:opacity-0",
        className
      )}
      {...props} />)
  );
})
SidebarMenuAction.displayName = "SidebarMenuAction"

const SidebarMenuBadge = React.forwardRef(({ className, ...props }, ref) => (
  <div
    ref={ref}
    data-sidebar="menu-badge"
    className={cn(
      "pointer-events-none absolute right-1 flex h-5 min-w-5 select-none items-center justify-center rounded-md px-1 text-xs font-medium tabular-nums text-sidebar-foreground",
      "peer-hover/menu-button:text-sidebar-accent-foreground peer-data-[active=true]/menu-button:text-sidebar-accent-foreground",
      "peer-data-[size=sm]/menu-button:top-1",
      "peer-data-[size=default]/menu-button:top-1.5",
      "peer-data-[size=lg]/menu-button:top-2.5",
      "group-data-[collapsible=icon]:hidden",
      className
    )}
    {...props} />
))
SidebarMenuBadge.displayName = "SidebarMenuBadge"

const SidebarMenuSkeleton = React.forwardRef(({ className, showIcon = false, ...props }, ref) => {
  // Random width between 50 to 90%.
  const width = React.useMemo(() => {
    return `${Math.floor(Math.random() * 40) + 50}%`;
  }, [])

  return (
    (<div
      ref={ref}
      data-sidebar="menu-skeleton"
      className={cn("flex h-8 items-center gap-2 rounded-md px-2", className)}
      {...props}>
      {showIcon && (
        <Skeleton className="size-4 rounded-md" data-sidebar="menu-skeleton-icon" />
      )}
      <Skeleton
        className="h-4 max-w-[--skeleton-width] flex-1"
        data-sidebar="menu-skeleton-text"
        style={
          {
            "--skeleton-width": width
          }
        } />
    </div>)
  );
})
SidebarMenuSkeleton.displayName = "SidebarMenuSkeleton"

const SidebarMenuSub = React.forwardRef(({ className, ...props }, ref) => (
  <ul
    ref={ref}
    data-sidebar="menu-sub"
    className={cn(
      "mx-3.5 flex min-w-0 translate-x-px flex-col gap-1 border-l border-sidebar-border px-2.5 py-0.5",
      "group-data-[collapsible=icon]:hidden",
      className
    )}
    {...props} />
))
SidebarMenuSub.displayName = "SidebarMenuSub"

const SidebarMenuSubItem = React.forwardRef(({ ...props }, ref) => <li ref={ref} {...props} />)
SidebarMenuSubItem.displayName = "SidebarMenuSubItem"

const SidebarMenuSubButton = React.forwardRef(
  ({ asChild = false, size = "md", isActive, className, ...props }, ref) => {
    const Comp = asChild ? Slot : "a"

    return (
      (<Comp
        ref={ref}
        data-sidebar="menu-sub-button"
        data-size={size}
        data-active={isActive}
        className={cn(
          "flex h-7 min-w-0 -translate-x-px items-center gap-2 overflow-hidden rounded-md px-2 text-sidebar-foreground outline-none ring-sidebar-ring hover:bg-sidebar-accent hover:text-sidebar-accent-foreground focus-visible:ring-2 active:bg-sidebar-accent active:text-sidebar-accent-foreground disabled:pointer-events-none disabled:opacity-50 aria-disabled:pointer-events-none aria-disabled:opacity-50 [&>span:last-child]:truncate [&>svg]:size-4 [&>svg]:shrink-0 [&>svg]:text-sidebar-accent-foreground",
          "data-[active=true]:bg-sidebar-accent data-[active=true]:text-sidebar-accent-foreground",
          size === "sm" && "text-xs",
          size === "md" && "text-sm",
          "group-data-[collapsible=icon]:hidden",
          className
        )}
        {...props} />)
    );
  }
)
SidebarMenuSubButton.displayName = "SidebarMenuSubButton"

export {
  Sidebar,
  SidebarContent,
  SidebarFooter,
  SidebarGroup,
  SidebarGroupAction,
  SidebarGroupContent,
  SidebarGroupLabel,
  SidebarHeader,
  SidebarInput,
  SidebarInset,
  SidebarMenu,
  SidebarMenuAction,
  SidebarMenuBadge,
  SidebarMenuButton,
  SidebarMenuItem,
  SidebarMenuSkeleton,
  SidebarMenuSub,
  SidebarMenuSubButton,
  SidebarMenuSubItem,
  SidebarProvider,
  SidebarRail,
  SidebarSeparator,
  SidebarTrigger,
  useSidebar,
}

```

---

## `src/components/ui/skeleton.jsx`

```javascript
import { cn } from "@/lib/utils"

function Skeleton({
  className,
  ...props
}) {
  return (
    (<div
      className={cn("animate-pulse rounded-md bg-primary/10", className)}
      {...props} />)
  );
}

export { Skeleton }

```

---

## `src/components/ui/slider.jsx`

```javascript
import * as React from "react"
import * as SliderPrimitive from "@radix-ui/react-slider"

import { cn } from "@/lib/utils"

const Slider = React.forwardRef(({ className, ...props }, ref) => (
  <SliderPrimitive.Root
    ref={ref}
    className={cn("relative flex w-full touch-none select-none items-center", className)}
    {...props}>
    <SliderPrimitive.Track
      className="relative h-1.5 w-full grow overflow-hidden rounded-full bg-primary/20">
      <SliderPrimitive.Range className="absolute h-full bg-primary" />
    </SliderPrimitive.Track>
    <SliderPrimitive.Thumb
      className="block h-4 w-4 rounded-full border border-primary/50 bg-background shadow transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50" />
  </SliderPrimitive.Root>
))
Slider.displayName = SliderPrimitive.Root.displayName

export { Slider }

```

---

## `src/components/ui/sonner.jsx`

```javascript
"use client";
import { useTheme } from "next-themes"
import { Toaster as Sonner } from "sonner"

const Toaster = ({
  ...props
}) => {
  const { theme = "system" } = useTheme()

  return (
    (<Sonner
      theme={theme}
      className="toaster group"
      toastOptions={{
        classNames: {
          toast:
            "group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
          description: "group-[.toast]:text-muted-foreground",
          actionButton:
            "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
          cancelButton:
            "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
        },
      }}
      {...props} />)
  );
}

export { Toaster }

```

---

## `src/components/ui/switch.jsx`

```javascript
import * as React from "react"
import * as SwitchPrimitives from "@radix-ui/react-switch"

import { cn } from "@/lib/utils"

const Switch = React.forwardRef(({ className, ...props }, ref) => (
  <SwitchPrimitives.Root
    className={cn(
      "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",
      className
    )}
    {...props}
    ref={ref}>
    <SwitchPrimitives.Thumb
      className={cn(
        "pointer-events-none block h-4 w-4 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
      )} />
  </SwitchPrimitives.Root>
))
Switch.displayName = SwitchPrimitives.Root.displayName

export { Switch }

```

---

## `src/components/ui/table.jsx`

```javascript
import * as React from "react"

import { cn } from "@/lib/utils"

const Table = React.forwardRef(({ className, ...props }, ref) => (
  <div className="relative w-full overflow-auto">
    <table
      ref={ref}
      className={cn("w-full caption-bottom text-sm", className)}
      {...props} />
  </div>
))
Table.displayName = "Table"

const TableHeader = React.forwardRef(({ className, ...props }, ref) => (
  <thead ref={ref} className={cn("[&_tr]:border-b", className)} {...props} />
))
TableHeader.displayName = "TableHeader"

const TableBody = React.forwardRef(({ className, ...props }, ref) => (
  <tbody
    ref={ref}
    className={cn("[&_tr:last-child]:border-0", className)}
    {...props} />
))
TableBody.displayName = "TableBody"

const TableFooter = React.forwardRef(({ className, ...props }, ref) => (
  <tfoot
    ref={ref}
    className={cn("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0", className)}
    {...props} />
))
TableFooter.displayName = "TableFooter"

const TableRow = React.forwardRef(({ className, ...props }, ref) => (
  <tr
    ref={ref}
    className={cn(
      "border-b transition-colors hover:bg-muted/50 data-[state=selected]:bg-muted",
      className
    )}
    {...props} />
))
TableRow.displayName = "TableRow"

const TableHead = React.forwardRef(({ className, ...props }, ref) => (
  <th
    ref={ref}
    className={cn(
      "h-10 px-2 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
      className
    )}
    {...props} />
))
TableHead.displayName = "TableHead"

const TableCell = React.forwardRef(({ className, ...props }, ref) => (
  <td
    ref={ref}
    className={cn(
      "p-2 align-middle [&:has([role=checkbox])]:pr-0 [&>[role=checkbox]]:translate-y-[2px]",
      className
    )}
    {...props} />
))
TableCell.displayName = "TableCell"

const TableCaption = React.forwardRef(({ className, ...props }, ref) => (
  <caption
    ref={ref}
    className={cn("mt-4 text-sm text-muted-foreground", className)}
    {...props} />
))
TableCaption.displayName = "TableCaption"

export {
  Table,
  TableHeader,
  TableBody,
  TableFooter,
  TableHead,
  TableRow,
  TableCell,
  TableCaption,
}

```

---

## `src/components/ui/tabs.jsx`

```javascript
import * as React from "react"
import * as TabsPrimitive from "@radix-ui/react-tabs"

import { cn } from "@/lib/utils"

const Tabs = TabsPrimitive.Root

const TabsList = React.forwardRef(({ className, ...props }, ref) => (
  <TabsPrimitive.List
    ref={ref}
    className={cn(
      "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
      className
    )}
    {...props} />
))
TabsList.displayName = TabsPrimitive.List.displayName

const TabsTrigger = React.forwardRef(({ className, ...props }, ref) => (
  <TabsPrimitive.Trigger
    ref={ref}
    className={cn(
      "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
      className
    )}
    {...props} />
))
TabsTrigger.displayName = TabsPrimitive.Trigger.displayName

const TabsContent = React.forwardRef(({ className, ...props }, ref) => (
  <TabsPrimitive.Content
    ref={ref}
    className={cn(
      "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      className
    )}
    {...props} />
))
TabsContent.displayName = TabsPrimitive.Content.displayName

export { Tabs, TabsList, TabsTrigger, TabsContent }

```

---

## `src/components/ui/textarea.jsx`

```javascript
import * as React from "react"

import { cn } from "@/lib/utils"

const Textarea = React.forwardRef(({ className, ...props }, ref) => {
  return (
    (<textarea
      className={cn(
        "flex min-h-[60px] w-full rounded-md border border-input bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",
        className
      )}
      ref={ref}
      {...props} />)
  );
})
Textarea.displayName = "Textarea"

export { Textarea }

```

---

## `src/components/ui/toast.jsx`

```javascript
import * as React from "react";
import * as ToastPrimitives from "@radix-ui/react-toast";
import { cva } from "class-variance-authority";
import { X } from "lucide-react";
import { cn } from "@/lib/utils";

const ToastProvider = ToastPrimitives.Provider;

const ToastViewport = React.forwardRef(({ className, ...props }, ref) => (
  <ToastPrimitives.Viewport
    ref={ref}
    className={cn(
      "fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
      className
    )}
    {...props}
  />
));
ToastViewport.displayName = ToastPrimitives.Viewport.displayName;

const toastVariants = cva(
  "group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",
  {
    variants: {
      variant: {
        default: "border bg-background text-foreground",
        destructive:
          "destructive group border-destructive bg-destructive text-destructive-foreground",
      },
    },
    defaultVariants: {
      variant: "default",
    },
  }
);

const Toast = React.forwardRef(({ className, variant, ...props }, ref) => {
  return (
    <ToastPrimitives.Root
      ref={ref}
      className={cn(toastVariants({ variant }), className)}
      {...props}
    />
  );
});
Toast.displayName = ToastPrimitives.Root.displayName;

const ToastAction = React.forwardRef(({ className, ...props }, ref) => (
  <ToastPrimitives.Action
    ref={ref}
    className={cn(
      "inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",
      className
    )}
    {...props}
  />
));
ToastAction.displayName = ToastPrimitives.Action.displayName;

const ToastClose = React.forwardRef(({ className, ...props }, ref) => (
  <ToastPrimitives.Close
    ref={ref}
    className={cn(
      "absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",
      className
    )}
    toast-close=""
    {...props}
  >
    <X className="h-4 w-4" />
  </ToastPrimitives.Close>
));
ToastClose.displayName = ToastPrimitives.Close.displayName;

const ToastTitle = React.forwardRef(({ className, ...props }, ref) => (
  <ToastPrimitives.Title
    ref={ref}
    className={cn("text-sm font-semibold", className)}
    {...props}
  />
));
ToastTitle.displayName = ToastPrimitives.Title.displayName;

const ToastDescription = React.forwardRef(({ className, ...props }, ref) => (
  <ToastPrimitives.Description
    ref={ref}
    className={cn("text-sm opacity-90", className)}
    {...props}
  />
));
ToastDescription.displayName = ToastPrimitives.Description.displayName;

export {
  ToastProvider,
  ToastViewport,
  Toast,
  ToastTitle,
  ToastDescription,
  ToastClose,
  ToastAction,
};

```

---

## `src/components/ui/toaster.jsx`

```javascript
import { useToast } from "@/components/ui/use-toast";
import {
  Toast,
  ToastClose,
  ToastDescription,
  ToastProvider,
  ToastTitle,
  ToastViewport,
} from "@/components/ui/toast";

export function Toaster() {
  const { toasts } = useToast();

  return (
    <ToastProvider>
      {toasts.map(function ({ id, title, description, action, ...props }) {
        return (
          <Toast key={id} {...props}>
            <div className="grid gap-1">
              {title && <ToastTitle>{title}</ToastTitle>}
              {description && (
                <ToastDescription>{description}</ToastDescription>
              )}
            </div>
            {action}
            <ToastClose />
          </Toast>
        );
      })}
      <ToastViewport />
    </ToastProvider>
  );
} 
```

---

## `src/components/ui/toggle-group.jsx`

```javascript
"use client";
import * as React from "react"
import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"

import { cn } from "@/lib/utils"
import { toggleVariants } from "@/components/ui/toggle"

const ToggleGroupContext = React.createContext({
  size: "default",
  variant: "default",
})

const ToggleGroup = React.forwardRef(({ className, variant, size, children, ...props }, ref) => (
  <ToggleGroupPrimitive.Root
    ref={ref}
    className={cn("flex items-center justify-center gap-1", className)}
    {...props}>
    <ToggleGroupContext.Provider value={{ variant, size }}>
      {children}
    </ToggleGroupContext.Provider>
  </ToggleGroupPrimitive.Root>
))

ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName

const ToggleGroupItem = React.forwardRef(({ className, children, variant, size, ...props }, ref) => {
  const context = React.useContext(ToggleGroupContext)

  return (
    (<ToggleGroupPrimitive.Item
      ref={ref}
      className={cn(toggleVariants({
        variant: context.variant || variant,
        size: context.size || size,
      }), className)}
      {...props}>
      {children}
    </ToggleGroupPrimitive.Item>)
  );
})

ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName

export { ToggleGroup, ToggleGroupItem }

```

---

## `src/components/ui/toggle.jsx`

```javascript
import * as React from "react"
import * as TogglePrimitive from "@radix-ui/react-toggle"
import { cva } from "class-variance-authority";

import { cn } from "@/lib/utils"

const toggleVariants = cva(
  "inline-flex items-center justify-center gap-2 rounded-md text-sm font-medium transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
  {
    variants: {
      variant: {
        default: "bg-transparent",
        outline:
          "border border-input bg-transparent shadow-sm hover:bg-accent hover:text-accent-foreground",
      },
      size: {
        default: "h-9 px-2 min-w-9",
        sm: "h-8 px-1.5 min-w-8",
        lg: "h-10 px-2.5 min-w-10",
      },
    },
    defaultVariants: {
      variant: "default",
      size: "default",
    },
  }
)

const Toggle = React.forwardRef(({ className, variant, size, ...props }, ref) => (
  <TogglePrimitive.Root
    ref={ref}
    className={cn(toggleVariants({ variant, size, className }))}
    {...props} />
))

Toggle.displayName = TogglePrimitive.Root.displayName

export { Toggle, toggleVariants }

```

---

## `src/components/ui/tooltip.jsx`

```javascript
"use client"

import * as React from "react"
import * as TooltipPrimitive from "@radix-ui/react-tooltip"

import { cn } from "@/lib/utils"

const TooltipProvider = TooltipPrimitive.Provider

const Tooltip = TooltipPrimitive.Root

const TooltipTrigger = TooltipPrimitive.Trigger

const TooltipContent = React.forwardRef(({ className, sideOffset = 4, ...props }, ref) => (
  <TooltipPrimitive.Portal>
    <TooltipPrimitive.Content
      ref={ref}
      sideOffset={sideOffset}
      className={cn(
        "z-50 overflow-hidden rounded-md bg-primary px-3 py-1.5 text-xs text-primary-foreground animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
        className
      )}
      {...props} />
  </TooltipPrimitive.Portal>
))
TooltipContent.displayName = TooltipPrimitive.Content.displayName

export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }

```

---

## `src/components/ui/use-toast.jsx`

```javascript
// Inspired by react-hot-toast library
import { useState, useEffect } from "react";

const TOAST_LIMIT = 20;
const TOAST_REMOVE_DELAY = 1000000;

const actionTypes = {
  ADD_TOAST: "ADD_TOAST",
  UPDATE_TOAST: "UPDATE_TOAST",
  DISMISS_TOAST: "DISMISS_TOAST",
  REMOVE_TOAST: "REMOVE_TOAST",
};

let count = 0;

function genId() {
  count = (count + 1) % Number.MAX_VALUE;
  return count.toString();
}

const toastTimeouts = new Map();

const addToRemoveQueue = (toastId) => {
  if (toastTimeouts.has(toastId)) {
    return;
  }

  const timeout = setTimeout(() => {
    toastTimeouts.delete(toastId);
    dispatch({
      type: actionTypes.REMOVE_TOAST,
      toastId,
    });
  }, TOAST_REMOVE_DELAY);

  toastTimeouts.set(toastId, timeout);
};

const _clearFromRemoveQueue = (toastId) => {
  const timeout = toastTimeouts.get(toastId);
  if (timeout) {
    clearTimeout(timeout);
    toastTimeouts.delete(toastId);
  }
};

export const reducer = (state, action) => {
  switch (action.type) {
    case actionTypes.ADD_TOAST:
      return {
        ...state,
        toasts: [action.toast, ...state.toasts].slice(0, TOAST_LIMIT),
      };

    case actionTypes.UPDATE_TOAST:
      return {
        ...state,
        toasts: state.toasts.map((t) =>
          t.id === action.toast.id ? { ...t, ...action.toast } : t
        ),
      };

    case actionTypes.DISMISS_TOAST: {
      const { toastId } = action;

      // ! Side effects ! - This could be extracted into a dismissToast() action,
      // but I'll keep it here for simplicity
      if (toastId) {
        addToRemoveQueue(toastId);
      } else {
        state.toasts.forEach((toast) => {
          addToRemoveQueue(toast.id);
        });
      }

      return {
        ...state,
        toasts: state.toasts.map((t) =>
          t.id === toastId || toastId === undefined
            ? {
                ...t,
                open: false,
              }
            : t
        ),
      };
    }
    case actionTypes.REMOVE_TOAST:
      if (action.toastId === undefined) {
        return {
          ...state,
          toasts: [],
        };
      }
      return {
        ...state,
        toasts: state.toasts.filter((t) => t.id !== action.toastId),
      };
  }
};

const listeners = [];

let memoryState = { toasts: [] };

function dispatch(action) {
  memoryState = reducer(memoryState, action);
  listeners.forEach((listener) => {
    listener(memoryState);
  });
}

function toast({ ...props }) {
  const id = genId();

  const update = (props) =>
    dispatch({
      type: actionTypes.UPDATE_TOAST,
      toast: { ...props, id },
    });

  const dismiss = () =>
    dispatch({ type: actionTypes.DISMISS_TOAST, toastId: id });

  dispatch({
    type: actionTypes.ADD_TOAST,
    toast: {
      ...props,
      id,
      open: true,
      onOpenChange: (open) => {
        if (!open) dismiss();
      },
    },
  });

  return {
    id,
    dismiss,
    update,
  };
}

function useToast() {
  const [state, setState] = useState(memoryState);

  useEffect(() => {
    listeners.push(setState);
    return () => {
      const index = listeners.indexOf(setState);
      if (index > -1) {
        listeners.splice(index, 1);
      }
    };
  }, [state]);

  return {
    ...state,
    toast,
    dismiss: (toastId) => dispatch({ type: actionTypes.DISMISS_TOAST, toastId }),
  };
}

export { useToast, toast }; 
```

---

## `src/hooks/use-mobile.jsx`

```javascript
import * as React from "react"

const MOBILE_BREAKPOINT = 768

export function useIsMobile() {
  const [isMobile, setIsMobile] = React.useState(undefined)

  React.useEffect(() => {
    const mql = window.matchMedia(`(max-width: ${MOBILE_BREAKPOINT - 1}px)`)
    const onChange = () => {
      setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
    }
    mql.addEventListener("change", onChange)
    setIsMobile(window.innerWidth < MOBILE_BREAKPOINT)
    return () => mql.removeEventListener("change", onChange);
  }, [])

  return !!isMobile
}

```

---

## `src/hooks/use-size.jsx`

```javascript
import * as React from "react"

export function useSize(ref) {
  const [size, setSize] = React.useState(null)

  // useLayoutEffect (not useEffect): the initial measurement must land before
  // the browser paints, so consumers can render their real content on the
  // very first painted frame instead of a guess. A ResizeObserver's first
  // callback arrives too late for that — by then an <img> src guess has
  // already been dispatched to the network.
  React.useLayoutEffect(() => {
    const element = ref.current
    if (!element) return

    const rect = element.getBoundingClientRect()
    setSize({ width: rect.width, height: rect.height })

    const observer = new ResizeObserver(([entry]) => {
      const { width, height } = entry.contentRect
      setSize({ width, height })
    })

    observer.observe(element)
    return () => observer.disconnect()
  }, [ref])

  return size
}

```

---

## `src/hooks/useAndroidBackButton.js`

```javascript
import { useEffect, useRef } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

/**
 * Handles Android hardware back-button navigation through WebView JS bridges.
 *
 * Many Android WebView wrappers invoke a global handler (e.g. window.onBackPressed)
 * when the hardware back button is pressed. We register such handlers and, when
 * called, navigate back through the in-app history stack. If we are already at the
 * root of the app, we hand control back to the native shell so it can exit or
 * move to the previous native screen.
 */
export function useAndroidBackButton() {
  const navigate = useNavigate();
  const location = useLocation();
  const historyDepth = useRef(0);

  // Track how deep we are in the in-app navigation stack
  useEffect(() => {
    historyDepth.current += 1;
  }, [location.pathname]);

  useEffect(() => {
    const handleBack = () => {
      if (historyDepth.current > 1) {
        navigate(-1);
        historyDepth.current = Math.max(0, historyDepth.current - 1);
        return true;
      }
      // At the root — defer to the native Android shell
      if (typeof window.Android !== 'undefined' && typeof window.Android.goBack === 'function') {
        window.Android.goBack();
      } else if (typeof window.ReactNativeWebView !== 'undefined' && typeof window.ReactNativeWebView.goBack === 'function') {
        window.ReactNativeWebView.goBack();
      }
      return false;
    };

    // Register on every common bridge surface the native shell might call
    window.onBackPressed = handleBack;
    window.handleAndroidBack = handleBack;
    if (typeof window.Android !== 'undefined') {
      window.Android.onBackPressed = handleBack;
    }

    return () => {
      delete window.onBackPressed;
      delete window.handleAndroidBack;
      if (typeof window.Android !== 'undefined' && window.Android.onBackPressed === handleBack) {
        delete window.Android.onBackPressed;
      }
    };
  }, [navigate]);
}
```

---

## `src/hooks/useCurrentUser.js`

```javascript
import { useState, useEffect } from 'react';
import { base44 } from '@/api/base44Client';

export function useCurrentUser() {
  const [user, setUser] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    let active = true;
    base44.auth.me()
      .then((u) => { if (active) { setUser(u); setLoading(false); } })
      .catch(() => { if (active) { setUser(null); setLoading(false); } });
    return () => { active = false; };
  }, []);
  return { user, loading, refresh: () => base44.auth.me().then(setUser) };
}
```

---

## `src/hooks/useHaptics.js`

```javascript
import { useCallback } from 'react';

/**
 * Provides haptic feedback on supported devices.
 * On iOS Safari (in a WebView/native shell), navigator.vibrate is typically
 * unavailable — this is a no-op there. On Android it triggers a short vibration.
 * Safe to call anywhere; silently does nothing if unsupported.
 */
export function useHaptics() {
  return useCallback((pattern = 10) => {
    try {
      if (typeof navigator !== 'undefined' && typeof navigator.vibrate === 'function') {
        navigator.vibrate(pattern);
      }
    } catch (e) {
      // no-op — haptics are a progressive enhancement
    }
  }, []);
}
```

---

## `src/hooks/useSeo.js`

```javascript
import { useEffect } from 'react';

// Default site-wide OG banner (1200x630) used when a page has no cover/avatar image.
const DEFAULT_OG_IMAGE = 'https://media.base44.com/images/public/6a83585d06d790bc1c169856/57b514fe8_generated_image.png';
const JSONLD_ID = 'dynamic-jsonld';

// Resolve a possibly-relative URL against the current origin so OG/canonical URLs are absolute.
function abs(url) {
  if (!url) return null;
  if (url.startsWith('http')) return url;
  return `${window.location.origin}${url.startsWith('/') ? '' : '/'}${url}`;
}

/**
 * useSeo — imperatively manages document title, meta tags, canonical link, and
 * a JSON-LD structured-data block for the current page. Tags are restored to
 * their prior (index.html default) values on cleanup, so navigating between
 * pages never leaks stale metadata.
 *
 * @param {object} opts
 * @param {string} [opts.title]      - document title + og/twitter title
 * @param {string} [opts.description] - meta description + og/twitter description
 * @param {string} [opts.image]      - og/twitter image (cover or avatar); falls back to site banner
 * @param {string} [opts.url]        - canonical + og:url (path or absolute)
 * @param {object} [opts.jsonLd]    - schema.org object injected as application/ld+json
 */
export function useSeo({ title, description, image, url, jsonLd } = {}) {
  useEffect(() => {
    // Don't touch the head until the page has real content to show.
    if (!title && !description) return;

    const managed = []; // { el, existed, attr, original }
    const setMeta = (selector, createAttrs, content) => {
      if (content == null) return;
      let el = document.head.querySelector(selector);
      let existed = false;
      let original = null;
      if (el) {
        existed = true;
        original = el.getAttribute('content');
      } else {
        el = document.createElement('meta');
        Object.entries(createAttrs).forEach(([k, v]) => el.setAttribute(k, v));
        document.head.appendChild(el);
      }
      el.setAttribute('content', content);
      managed.push({ el, existed, original });
    };
    const setLink = (rel, href) => {
      if (href == null) return;
      let el = document.head.querySelector(`link[rel="${rel}"]`);
      let existed = false;
      let original = null;
      if (el) {
        existed = true;
        original = el.getAttribute('href');
      } else {
        el = document.createElement('link');
        el.setAttribute('rel', rel);
        document.head.appendChild(el);
      }
      el.setAttribute('href', href);
      managed.push({ el, existed, original });
    };

    const prevTitle = document.title;
    if (title) document.title = title;

    const imageUrl = abs(image || DEFAULT_OG_IMAGE);
    const canonicalUrl = abs(url);

    setMeta('meta[name="description"]', { name: 'description' }, description);
    setMeta('meta[property="og:title"]', { property: 'og:title' }, title);
    setMeta('meta[property="og:description"]', { property: 'og:description' }, description);
    setMeta('meta[property="og:image"]', { property: 'og:image' }, imageUrl);
    setMeta('meta[property="og:url"]', { property: 'og:url' }, canonicalUrl);
    setMeta('meta[name="twitter:title"]', { name: 'twitter:title' }, title);
    setMeta('meta[name="twitter:description"]', { name: 'twitter:description' }, description);
    setMeta('meta[name="twitter:image"]', { name: 'twitter:image' }, imageUrl);
    setLink('canonical', canonicalUrl);

    let jsonLdEl = null;
    if (jsonLd) {
      jsonLdEl = document.getElementById(JSONLD_ID);
      if (!jsonLdEl) {
        jsonLdEl = document.createElement('script');
        jsonLdEl.type = 'application/ld+json';
        jsonLdEl.id = JSONLD_ID;
        document.head.appendChild(jsonLdEl);
      }
      jsonLdEl.textContent = JSON.stringify(jsonLd);
    }

    return () => {
      managed.forEach(({ el, existed, original }) => {
        if (!el.parentNode) return;
        if (existed) {
          if (original == null) el.removeAttribute('content');
          else el.setAttribute('content', original);
        } else {
          el.parentNode.removeChild(el);
        }
      });
      document.title = prevTitle;
      if (jsonLdEl && jsonLdEl.parentNode) jsonLdEl.parentNode.removeChild(jsonLdEl);
    };
  }, [title, description, image, url, JSON.stringify(jsonLd)]);
}

export { DEFAULT_OG_IMAGE };
```

---

## `src/hooks/useSystemTheme.js`

```javascript
import { useEffect } from 'react';

/**
 * Automatically syncs the OS prefers-color-scheme with the Tailwind `.dark` class
 * on <html>. Applies on mount and reacts to system theme changes.
 */
export function useSystemTheme() {
  useEffect(() => {
    const mq = window.matchMedia('(prefers-color-scheme: dark)');
    const apply = () => {
      document.documentElement.classList.toggle('dark', mq.matches);
    };
    apply();
    mq.addEventListener('change', apply);
    return () => mq.removeEventListener('change', apply);
  }, []);
}
```

---

## `src/index.css`

```css
@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  :root {
    --background: 125 45% 97%;
    --foreground: 219 38% 16%;
    --card: 0 0% 100%;
    --card-foreground: 219 38% 16%;
    --popover: 0 0% 100%;
    --popover-foreground: 219 38% 16%;
    --primary: 219 90% 66%;
    --primary-foreground: 219 45% 14%;
    --secondary: 186 55% 75%;
    --secondary-foreground: 219 45% 16%;
    --muted: 186 30% 94%;
    --muted-foreground: 219 25% 42%;
    --accent: 125 85% 85%;
    --accent-foreground: 219 45% 16%;
    --destructive: 0 68% 48%;
    --destructive-foreground: 0 0% 100%;
    --border: 186 28% 88%;
    --input: 186 28% 88%;
    --ring: 219 90% 66%;
    --chart-1: 219 90% 66%;
    --chart-2: 186 55% 75%;
    --chart-3: 125 80% 72%;
    --chart-4: 200 70% 60%;
    --chart-5: 160 55% 55%;
    --radius: 0.5rem;
    --font-heading: ui-sans-serif, system-ui, sans-serif;
    --font-body: ui-sans-serif, system-ui, sans-serif;
    --font-display: ui-sans-serif, system-ui, sans-serif;
    --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    --sidebar-background: 0 0% 98%;
    --sidebar-foreground: 240 5.3% 26.1%;
    --sidebar-primary: 240 5.9% 10%;
    --sidebar-primary-foreground: 0 0% 98%;
    --sidebar-accent: 240 4.8% 95.9%;
    --sidebar-accent-foreground: 240 5.9% 10%;
    --sidebar-border: 220 13% 91%;
    --sidebar-ring: 217.2 91.2% 59.8%;
  }

  .dark {
    --background: 215 42% 10%;
    --foreground: 186 40% 92%;
    --card: 215 38% 13%;
    --card-foreground: 186 40% 92%;
    --popover: 215 38% 13%;
    --popover-foreground: 186 40% 92%;
    --primary: 219 90% 70%;
    --primary-foreground: 215 45% 10%;
    --secondary: 186 40% 28%;
    --secondary-foreground: 186 40% 92%;
    --muted: 215 35% 18%;
    --muted-foreground: 186 25% 65%;
    --accent: 125 65% 70%;
    --accent-foreground: 215 45% 10%;
    --destructive: 0 62% 48%;
    --destructive-foreground: 186 40% 92%;
    --border: 215 32% 22%;
    --input: 215 32% 22%;
    --ring: 219 90% 70%;
    --chart-1: 219 90% 70%;
    --chart-2: 186 55% 70%;
    --chart-3: 125 70% 68%;
    --chart-4: 200 70% 62%;
    --chart-5: 160 55% 58%;
    --sidebar-background: 240 5.9% 10%;
    --sidebar-foreground: 240 4.8% 95.9%;
    --sidebar-primary: 224.3 76.3% 48%;
    --sidebar-primary-foreground: 0 0% 100%;
    --sidebar-accent: 240 3.7% 15.9%;
    --sidebar-accent-foreground: 240 4.8% 95.9%;
    --sidebar-border: 240 3.7% 15.9%;
    --sidebar-ring: 217.2 91.2% 59.8%;
  }
}



@layer base {
  * {
    @apply border-border outline-ring/50;
  }

  body {
    @apply bg-background text-foreground font-body;
  }
}

@layer components {
  .prose-folio h1 { font-size: 1.5rem; font-weight: 600; margin-top: 1.5em; }
  .prose-folio h2 { font-size: 1.25rem; font-weight: 600; margin-top: 1.4em; }
  .prose-folio h3 { font-size: 1.1rem; font-weight: 600; margin-top: 1.2em; }
  .prose-folio p { margin-bottom: 1em; }
  .prose-folio blockquote { border-left: 3px solid hsl(var(--border)); padding-left: 1rem; color: hsl(var(--muted-foreground)); font-style: italic; margin: 1em 0; }
  .prose-folio ul { list-style: disc; padding-left: 1.5rem; margin-bottom: 1em; }
  .prose-folio ol { list-style: decimal; padding-left: 1.5rem; margin-bottom: 1em; }
}

.ql-editor { min-height: 320px; font-size: 16px; }

/* iOS WebView enhancements */
html, body {
  overscroll-behavior: none;
  -webkit-overscroll-behavior: none;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  -webkit-tap-highlight-color: transparent;
  text-rendering: optimizeLegibility;
}

/* iOS-style momentum scrolling */
.scroll-touch {
  -webkit-overflow-scrolling: touch;
  scroll-behavior: smooth;
}

/* iOS active state — subtle scale on tap for buttons */
button:active:not(:disabled),
[role="button"]:active,
a:active {
  transform: scale(0.97);
  transition: transform 0.1s ease-out;
}

/* Larger touch targets on mobile */
@media (pointer: coarse) {
  button, [role="button"], a {
    min-height: 44px;
  }
}

/* Disable text selection on interactive elements; keep body text selectable */
button, a, [role="button"], [role="tab"], nav, svg, img {
  -webkit-user-select: none;
  user-select: none;
  -webkit-touch-callout: none;
}

/* Native-feeling page slide transition */
@keyframes page-slide {
  from { opacity: 0; transform: translateX(10px); }
  to { opacity: 1; transform: translateX(0); }
}

.page-slide {
  animation: page-slide 0.22s ease-out;
}
```

---

## `src/lib/AuthContext.jsx`

```javascript
import React, { createContext, useState, useContext, useEffect } from 'react';
import { base44 } from '@/api/base44Client';
import { appParams } from '@/lib/app-params';
import { createAxiosClient } from '@base44/sdk/dist/utils/axios-client';

const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  const [isLoadingAuth, setIsLoadingAuth] = useState(true);
  const [isLoadingPublicSettings, setIsLoadingPublicSettings] = useState(true);
  const [authError, setAuthError] = useState(null);
  const [authChecked, setAuthChecked] = useState(false);
  const [appPublicSettings, setAppPublicSettings] = useState(null); // Contains only { id, public_settings }

  useEffect(() => {
    checkAppState();
  }, []);

  const checkAppState = async () => {
    try {
      setIsLoadingPublicSettings(true);
      setAuthError(null);
      
      // First, check app public settings (with token if available)
      // This will tell us if auth is required, user not registered, etc.
      const appClient = createAxiosClient({
        baseURL: `/api/apps/public`,
        headers: {
          'X-App-Id': appParams.appId
        },
        token: appParams.token, // Include token if available
        interceptResponses: true
      });
      
      try {
        const publicSettings = await appClient.get(`/prod/public-settings/by-id/${appParams.appId}`);
        setAppPublicSettings(publicSettings);
        
        // If we got the app public settings successfully, check if user is authenticated
        if (appParams.token) {
          await checkUserAuth();
        } else {
          setIsLoadingAuth(false);
          setIsAuthenticated(false);
          setAuthChecked(true);
        }
        setIsLoadingPublicSettings(false);
      } catch (appError) {
        console.error('App state check failed:', appError);
        
        // Handle app-level errors
        if (appError.status === 403 && appError.data?.extra_data?.reason) {
          const reason = appError.data.extra_data.reason;
          if (reason === 'auth_required') {
            setAuthError({
              type: 'auth_required',
              message: 'Authentication required'
            });
          } else if (reason === 'user_not_registered') {
            setAuthError({
              type: 'user_not_registered',
              message: 'User not registered for this app'
            });
          } else {
            setAuthError({
              type: reason,
              message: appError.message
            });
          }
        } else {
          setAuthError({
            type: 'unknown',
            message: appError.message || 'Failed to load app'
          });
        }
        setIsLoadingPublicSettings(false);
        setIsLoadingAuth(false);
      }
    } catch (error) {
      console.error('Unexpected error:', error);
      setAuthError({
        type: 'unknown',
        message: error.message || 'An unexpected error occurred'
      });
      setIsLoadingPublicSettings(false);
      setIsLoadingAuth(false);
    }
  };

  const checkUserAuth = async () => {
    try {
      // Now check if the user is authenticated
      setIsLoadingAuth(true);
      const currentUser = await base44.auth.me();
      setUser(currentUser);
      setIsAuthenticated(true);
      setIsLoadingAuth(false);
      setAuthChecked(true);
    } catch (error) {
      console.error('User auth check failed:', error);
      setIsLoadingAuth(false);
      setIsAuthenticated(false);
      setAuthChecked(true);
      
      // If user auth fails, it might be an expired token
      if (error.status === 401 || error.status === 403) {
        setAuthError({
          type: 'auth_required',
          message: 'Authentication required'
        });
      }
    }
  };

  const logout = (shouldRedirect = true) => {
    setUser(null);
    setIsAuthenticated(false);
    
    if (shouldRedirect) {
      // Use the SDK's logout method which handles token cleanup and redirect
      base44.auth.logout(window.location.href);
    } else {
      // Just remove the token without redirect
      base44.auth.logout();
    }
  };

  const navigateToLogin = () => {
    // Use the SDK's redirectToLogin method
    base44.auth.redirectToLogin(window.location.href);
  };

  return (
    <AuthContext.Provider value={{ 
      user, 
      isAuthenticated, 
      isLoadingAuth,
      isLoadingPublicSettings,
      authError,
      appPublicSettings,
      authChecked,
      logout,
      navigateToLogin,
      checkUserAuth,
      checkAppState
    }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

```

---

## `src/lib/PageNotFound.jsx`

```javascript
import { useLocation } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useQuery } from '@tanstack/react-query';


export default function PageNotFound({}) {
    const location = useLocation();
    const pageName = location.pathname.substring(1);

    const { data: authData, isFetched } = useQuery({
        queryKey: ['user'],
        queryFn: async () => {
            try {
                const user = await base44.auth.me();
                return { user, isAuthenticated: true };
            } catch (error) {
                return { user: null, isAuthenticated: false };
            }
        }
    });
    
    return (
        <div className="min-h-screen flex items-center justify-center p-6 bg-slate-50">
            <div className="max-w-md w-full">
                <div className="text-center space-y-6">
                    {/* 404 Error Code */}
                    <div className="space-y-2">
                        <h1 className="text-7xl font-light text-slate-300">404</h1>
                        <div className="h-0.5 w-16 bg-slate-200 mx-auto"></div>
                    </div>
                    
                    {/* Main Message */}
                    <div className="space-y-3">
                        <h2 className="text-2xl font-medium text-slate-800">
                            Page Not Found
                        </h2>
                        <p className="text-slate-600 leading-relaxed">
                            The page <span className="font-medium text-slate-700">"{pageName}"</span> could not be found in this application.
                        </p>
                    </div>
                    
                    {/* Admin Note */}
                    {isFetched && authData.isAuthenticated && authData.user?.role === 'admin' && (
                        <div className="mt-8 p-4 bg-slate-100 rounded-lg border border-slate-200">
                            <div className="flex items-start space-x-3">
                                <div className="flex-shrink-0 w-5 h-5 rounded-full bg-orange-100 flex items-center justify-center mt-0.5">
                                    <div className="w-2 h-2 rounded-full bg-orange-400"></div>
                                </div>
                                <div className="text-left space-y-1">
                                    <p className="text-sm font-medium text-slate-700">Admin Note</p>
                                    <p className="text-sm text-slate-600 leading-relaxed">
                                        This could mean that the AI hasn't implemented this page yet. Ask it to implement it in the chat.
                                    </p>
                                </div>
                            </div>
                        </div>
                    )}
                    
                    {/* Action Button */}
                    <div className="pt-6">
                        <button 
                            onClick={() => window.location.href = '/'} 
                            className="inline-flex items-center px-4 py-2 text-sm font-medium text-slate-700 bg-white border border-slate-200 rounded-lg hover:bg-slate-50 hover:border-slate-300 transition-colors duration-200 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-slate-500"
                        >
                            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6" />
                            </svg>
                            Go Home
                        </button>
                    </div>
                </div>
            </div>
        </div>
    )
}
```

---

## `src/lib/app-params.js`

```javascript
const isNode = typeof window === 'undefined';
const windowObj = isNode ? { localStorage: new Map() } : window;
const storage = windowObj.localStorage;

const toSnakeCase = (str) => {
	return str.replace(/([A-Z])/g, '_$1').toLowerCase();
}

const getAppParamValue = (paramName, { defaultValue = undefined, removeFromUrl = false } = {}) => {
	if (isNode) {
		return defaultValue;
	}
	const storageKey = `base44_${toSnakeCase(paramName)}`;
	const urlParams = new URLSearchParams(window.location.search);
	const searchParam = urlParams.get(paramName);
	if (removeFromUrl) {
		urlParams.delete(paramName);
		const newUrl = `${window.location.pathname}${urlParams.toString() ? `?${urlParams.toString()}` : ""
			}${window.location.hash}`;
		window.history.replaceState({}, document.title, newUrl);
	}
	if (searchParam) {
		storage.setItem(storageKey, searchParam);
		return searchParam;
	}
	if (defaultValue) {
		storage.setItem(storageKey, defaultValue);
		return defaultValue;
	}
	const storedValue = storage.getItem(storageKey);
	if (storedValue) {
		return storedValue;
	}
	return null;
}

const getAppParams = () => {
	if (getAppParamValue("clear_access_token") === 'true') {
		storage.removeItem('base44_access_token');
		storage.removeItem('token');
	}
	return {
		appId: getAppParamValue("app_id", { defaultValue: import.meta.env.VITE_BASE44_APP_ID }),
		token: getAppParamValue("access_token", { removeFromUrl: true }),
		fromUrl: getAppParamValue("from_url", { defaultValue: window.location.href }),
		functionsVersion: getAppParamValue("functions_version", { defaultValue: import.meta.env.VITE_BASE44_FUNCTIONS_VERSION }),
		appBaseUrl: getAppParamValue("app_base_url", { defaultValue: import.meta.env.VITE_BASE44_APP_BASE_URL }),
	}
}


export const appParams = {
	...getAppParams()
}

```

---

## `src/lib/authMfa.js`

```javascript
import { appParams } from '@/lib/app-params';
import { base44 } from '@/api/base44Client';

function authPath(suffix) {
  if (!/^[a-f0-9]{24}$/i.test(appParams.appId)) throw new Error('Invalid app ID');
  return `/api/apps/${appParams.appId}/auth/${suffix}`;
}

async function post(suffix, body, token) {
  const response = await fetch(authPath(suffix), {
    method: 'POST',
    credentials: 'include',
    headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}) },
    body: JSON.stringify(body),
  });
  const result = await response.json();
  if (!response.ok) throw new Error(result.error?.message || result.detail || 'Unable to sign in');
  return result;
}

export async function loginWithMfa(email, password) {
  const result = await post('login', { email, password });
  if (result.access_token) base44.auth.setToken(result.access_token);
  return result;
}

export async function continueMfa(result, returnTo) {
  const encode = bytes => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
  const verifier = encode(crypto.getRandomValues(new Uint8Array(32)));
  const challenge = encode(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
  const { code } = await post('mfa/handoff', { code_challenge: challenge }, result.mfa_session_token);
  sessionStorage.setItem(`app-mfa-pkce:${appParams.appId}`, verifier);
  const url = new URL('/auth/mfa', window.location.origin);
  url.search = new URLSearchParams({ app_id: appParams.appId, mfa_code: code, from_url: returnTo });
  window.location.assign(url.href);
}

// provider: 'google' | 'microsoft' | 'facebook' | 'apple'
export async function loginWithSocial(provider, returnTo) {
  const response = await fetch(`/api/apps/public/login-info/by-id/${appParams.appId}`);
  if (!response.ok) throw new Error('Unable to load sign-in options');
  const info = await response.json();
  if (info.auth_config?.mfa_policy !== 'required') return base44.auth.loginWithProvider(provider, returnTo);
  const url = new URL('/auth/mfa', window.location.origin);
  url.search = new URLSearchParams({ app_id: appParams.appId, oauth_start: provider, from_url: returnTo });
  window.location.assign(url.href);
}

export function loginWithGoogle(returnTo) {
  return loginWithSocial('google', returnTo);
}

```

---

## `src/lib/authMfaFlow.js`

```javascript
import { base44 } from '@/api/base44Client';
import { appParams } from '@/lib/app-params';

// The app's own MFA: sign-in challenge, enrollment and factor management, against the app's
// /api/apps/<id>/auth/mfa routes. Credentials stay in memory, never in the URL or storage.

const PKCE_KEY = () => `app-mfa-pkce:${appParams.appId}`;
const encode = bytes => btoa(String.fromCharCode(...bytes)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');

export class MfaError extends Error {
  constructor(message, status, retryAfter) {
    super(message);
    this.status = status;
    this.retryAfter = retryAfter;
  }
  // The challenge or grant is gone (expired or used up): sign in again. A 409 is either a concurrent
  // change or the last-method guard; its message says which, so it gets no sign-in link.
  get mustSignInAgain() {
    return this.status === 401;
  }
}

function authPath(suffix) {
  if (!/^[a-f0-9]{24}$/i.test(appParams.appId)) throw new Error('Invalid app ID');
  return `/api/apps/${appParams.appId}/auth/${suffix}`;
}

async function request(suffix, { method = 'POST', body, token, headers } = {}) {
  const response = await fetch(authPath(suffix), {
    method,
    credentials: 'include',
    headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: `Bearer ${token}` } : {}), ...headers },
    body: body === undefined ? undefined : JSON.stringify(body),
  });
  const result = await response.json().catch(() => ({}));
  if (!response.ok) {
    const message = result.error?.message || result.detail || 'Something went wrong. Try again.';
    throw new MfaError(message, response.status, Number(response.headers.get('Retry-After')) || null);
  }
  return result;
}

// One MFA credential (sign-in challenge, then the management grant) and every call made with it.
// Each success may rotate the grant and revoke older sessions, so both are swapped every time.
export function mfaSession(challenge) {
  let credential = challenge.mfa_session_token;
  const call = async (suffix, body, method) => {
    const result = await request(`mfa/${suffix}`, { method, body, token: credential });
    if (result.mfa_management_token) credential = result.mfa_management_token;
    if (result.access_token) base44.auth.setToken(result.access_token);
    return result;
  };
  return {
    // Sign-in with an enrolled method. method: 'totp' | 'sms'
    verify: (code, method, rememberDevice) => call('verify', { code, method, remember_device: rememberDevice }),
    sendSignInCode: () => call('resend'),
    // Enrollment, and adding or replacing a method during management.
    setupAuthenticator: () => call('totp/setup', {}),
    confirmAuthenticator: (code, rememberDevice = false) => call('totp/verify', { code, remember_device: rememberDevice }),
    sendPhoneCode: phoneNumber => call('sms/send-code', { phone_number: phoneNumber }),
    confirmPhone: (code, rememberDevice = false) => call('sms/verify', { code, remember_device: rememberDevice }),
    // Management only.
    status: () => call('status', undefined, 'GET'),
    sendProofCode: () => call('sms/send-code', { phone_number: '' }),
    removeMethod: (method, code, proofMethod) => call('disable', { method, code, verification_method: proofMethod }),
    forgetDevices: (code, proofMethod) => call('trusted-devices/clear', { code, method: proofMethod }),
  };
}

// Password sign-in that opens factor management instead of signing in.
export function signInToManageMfa(email, password) {
  return request('login', { body: { email, password }, headers: { 'X-App-Mfa-Action': 'manage' } });
}

let resumed;

// Picks up the challenge a social or SSO sign-in sends back to /mfa?mfa_code=…
export function resumeMfa() {
  // The code works once, so a second call (e.g. React StrictMode) reuses the first exchange.
  resumed ||= (async () => {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('mfa_code');
    if (!code) return null;
    const verifier = sessionStorage.getItem(PKCE_KEY());
    sessionStorage.removeItem(PKCE_KEY());
    params.delete('mfa_code');
    const rest = params.toString();
    window.history.replaceState(null, '', `${window.location.pathname}${rest ? `?${rest}` : ''}`);
    const result = await request('mfa/exchange', { body: { code, code_verifier: verifier } });
    if (result.access_token) base44.auth.setToken(result.access_token);
    return result;
  })();
  return resumed;
}

const isInAppBrowser = () => /LinkedIn|Twitter/i.test(navigator.userAgent);

// The app's sign-in settings: auth_config holds mfa_policy and the enabled sign-in methods.
export async function loadSignInOptions() {
  const response = await fetch(`/api/apps/public/login-info/by-id/${appParams.appId}`);
  if (!response.ok) throw new Error('Unable to load sign-in options');
  return response.json();
}

// provider: 'google' | 'microsoft' | 'facebook' | 'apple' | 'sso'. With manage, the sign-in opens
// factor management. Returns to this app's /mfa page when MFA is needed.
export async function signInWithProvider(provider, returnTo, { manage = false } = {}) {
  const info = await loadSignInOptions();
  // Enterprise SSO sign-in is exempt from Base44 MFA; only managing factors asks for it.
  if (!manage && (info.auth_config?.mfa_policy !== 'required' || provider === 'sso')) {
    return base44.auth.loginWithProvider(provider, returnTo);
  }
  if (isInAppBrowser()) {
    // In-app browsers hand sign-in to the system browser through the platform's MFA page.
    const url = new URL('/auth/mfa', window.location.origin);
    url.search = new URLSearchParams({ app_id: appParams.appId, oauth_start: provider, from_url: returnTo, ...(manage ? { security: '1' } : {}) });
    window.location.assign(url.href);
    return;
  }
  const verifier = encode(crypto.getRandomValues(new Uint8Array(32)));
  const challenge = encode(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))));
  sessionStorage.setItem(PKCE_KEY(), verifier);
  const workspaceSso = provider === 'sso' && info.auth_config?.use_workspace_sso && info.organization_id;
  const path = provider === 'sso'
    ? (workspaceSso ? `/api/apps/${info.organization_id}/${appParams.appId}/auth/sso/login` : `/api/apps/${appParams.appId}/auth/sso/login`)
    : `/api/apps/auth${provider === 'google' ? '' : `/${provider}`}/login`;
  const url = new URL(path, window.location.origin);
  url.search = new URLSearchParams({
    from_url: new URL(returnTo, window.location.origin).href,
    ...(workspaceSso ? {} : { app_id: appParams.appId }),
    ...(manage ? { app_mfa_action: 'manage' } : {}),
    app_mfa_code_challenge: challenge,
    app_mfa_return: '/mfa',
  });
  window.location.assign(url.href);
}

// After MFA: a popup sign-in hands the session to the window that opened it; otherwise go on.
export function finishSignIn(accessToken, returnTo) {
  if (new URLSearchParams(window.location.search).get('popup') === '1' && window.opener) {
    window.opener.postMessage({ access_token: accessToken }, window.location.origin);
    window.close();
    return;
  }
  window.location.href = returnTo;
}

```

---

## `src/lib/authReturnTo.js`

```javascript
// Shared by the auth pages (Login, Register, and any page that resumes a flow
// after sign-in, e.g. the MCP OAuth consent page). Keep the redirect
// validation in one place — it is security-sensitive and easy to drift.

// Resolve ?returnTo= to a safe same-origin path, else "/".
//
// The same-origin check alone is not enough: a value like /.//evil.com or
// /\evil.com parses same-origin but normalizes to a protocol-relative
// //evil.com when assigned to location.href — an open redirect. So require the
// resolved path to be exactly one leading slash (no "//" prefix, no backslash).
export function safeReturnTo() {
  const raw = new URLSearchParams(window.location.search).get("returnTo");
  if (!raw) return "/";
  try {
    const url = new URL(raw, window.location.origin);
    if (url.origin !== window.location.origin) return "/";
    // Strip app-bootstrap params: app-params.js persists these from the URL into
    // localStorage before the SDK initializes, so a crafted returnTo could
    // otherwise poison the freshly issued session — repointing the app at an
    // attacker's backend (app_base_url/app_id/functions_version) or overwriting
    // the token. Normal app-flow params (e.g. the OAuth consent ctx) are kept.
    // The full app-params.js bootstrap set (src/lib/app-params.js) — any of
    // these in a crafted returnTo would be persisted at next load.
    for (const p of ["access_token", "clear_access_token", "app_id", "app_base_url", "functions_version", "from_url"]) {
      url.searchParams.delete(p);
    }
    const path = url.pathname + url.search;
    if (!path.startsWith("/") || path.startsWith("//") || path.includes("\\")) return "/";
    return path;
  } catch {
    return "/";
  }
}

```

---

## `src/lib/citations.js`

```javascript
const SITE = 'https://chapterly.ariamalik.com';

/**
 * Build formal citation strings in multiple formats for a published research paper.
 * @param {object} paper - ResearchPaper record
 * @returns {object} { apa, mla, chicago, harvard, bibtex, html, markdown }
 */
export function buildCitations(paper) {
  const url = `${SITE}/research/${paper.id}`;
  const year = paper.published_date ? new Date(paper.published_date).getFullYear() : new Date().getFullYear();
  const authors = paper.authors && paper.authors.length ? paper.authors : ['Anonymous'];
  const authorsStr = authors.join(', ');
  const cid = paper.citation_id || '';

  return {
    apa: `${authorsStr} (${year}). ${paper.title}. Chapterly. ${url}${cid ? ` (Citation ID: ${cid})` : ''}`,
    mla: `${authorsStr}. "${paper.title}." Chapterly, ${year}, ${url}.`,
    chicago: `${authorsStr}. "${paper.title}." Chapterly, ${year}. ${url}.`,
    harvard: `${authorsStr} ${year}, '${paper.title}', Chapterly, viewed at ${url}.`,
    bibtex: `@article{${cid || 'chapterly_' + paper.id},
  title   = {${paper.title}},
  author  = {${authorsStr}},
  year    = {${year}},
  publisher = {Chapterly},
  url     = {${url}},${cid ? `\n  note    = {Citation ID: ${cid}}` : ''}
}`,
    html: `<a href="${url}">${authorsStr} (${year}). ${paper.title}. Chapterly.</a>${cid ? ` <small>Citation ID: ${cid}</small>` : ''}`,
    markdown: `[${authorsStr} (${year}). ${paper.title}. Chapterly.](${url})${cid ? ` (Citation ID: ${cid})` : ''}`,
  };
}

export { SITE };
```

---

## `src/lib/genres.js`

```javascript
import { base44 } from '@/api/base44Client';

// Fallback taxonomy: only used when the shared genre list cannot be loaded.
export const DEFAULT_GENRES = [
  'Fantasy', 'Romance', 'Mystery', 'Sci-Fi', 'Thriller', 'Horror',
  'Young Adult', 'Literary', 'Historical', 'Adventure', 'Drama', 'Fanfiction', 'Other',
];

export async function loadGenres() {
  const rows = await base44.entities.Genre.list('-created_date', 400);
  return rows || [];
}

const byName = (a, b) => a.localeCompare(b);

/** Names of the top-level genres, including any created by the community. */
export function topLevelNames(genres) {
  const names = (genres || []).filter((g) => !g.parent_id && g.name).map((g) => g.name);
  const unique = [...new Set(names)];
  return (unique.length ? unique : DEFAULT_GENRES).sort(byName);
}

export function genreIdFor(genres, name) {
  const target = String(name || '').toLowerCase();
  const match = (genres || []).find((g) => !g.parent_id && g.name?.toLowerCase() === target);
  return match?.id || null;
}

/** Sub-category names belonging to one top-level genre. */
export function subGenreNames(genres, parentName) {
  const parentId = genreIdFor(genres, parentName);
  if (!parentId) return [];
  const names = (genres || []).filter((g) => g.parent_id === parentId && g.name).map((g) => g.name);
  return [...new Set(names)].sort(byName);
}

/** Creates a genre (parentId empty) or sub-category, reusing an existing match. */
export async function createGenre({ name, parentId, description }) {
  const clean = String(name || '').trim();
  if (!clean) throw new Error('Give the category a name');
  const rows = await loadGenres();
  const existing = rows.find(
    (g) => (g.parent_id || '') === (parentId || '') && (g.name || '').toLowerCase() === clean.toLowerCase()
  );
  if (existing) return existing;
  return base44.entities.Genre.create({
    name: clean,
    parent_id: parentId || '',
    description: description || '',
  });
}
```

---

## `src/lib/paperPdf.js`

```javascript
import { jsPDF } from 'jspdf';
import { buildCitations } from '@/lib/citations';

function htmlToBlocks(html) {
  const doc = new DOMParser().parseFromString(html, 'text/html');
  const blocks = [];
  doc.body.childNodes.forEach((node) => {
    if (node.nodeType === 3) {
      const t = node.textContent.trim();
      if (t) blocks.push({ type: 'p', text: t });
      return;
    }
    if (node.nodeType !== 1) return;
    const tag = node.tagName.toLowerCase();
    if (['h1', 'h2', 'h3', 'h4'].includes(tag)) {
      const t = node.textContent.trim();
      if (t) blocks.push({ type: 'h', level: Number(tag[1]), text: t });
    } else if (tag === 'blockquote') {
      const t = node.textContent.trim();
      if (t) blocks.push({ type: 'quote', text: t });
    } else if (tag === 'ul' || tag === 'ol') {
      node.querySelectorAll(':scope > li').forEach((li, i) => {
        const t = li.textContent.trim();
        if (t) blocks.push({ type: 'li', bullet: tag === 'ol' ? `${i + 1}.` : '•', text: t });
      });
    } else {
      const t = node.textContent.trim();
      if (t) blocks.push({ type: 'p', text: t });
    }
  });
  return blocks;
}

export async function downloadPaperPdf(paper) {
  const c = buildCitations(paper);
  const year = paper.published_date ? new Date(paper.published_date).getFullYear() : new Date().getFullYear();

  const doc = new jsPDF({ unit: 'pt', format: 'a4' });
  const pageW = doc.internal.pageSize.getWidth();
  const pageH = doc.internal.pageSize.getHeight();
  const margin = 56;
  const contentW = pageW - margin * 2;
  let y = margin;

  const ensure = (h) => {
    if (y + h > pageH - margin) { doc.addPage(); y = margin; }
  };

  doc.setFont('helvetica', 'bold'); doc.setFontSize(11); doc.setTextColor(59, 130, 246);
  doc.text('Chapterly', margin, y);
  doc.setTextColor(150, 150, 150); doc.setFont('helvetica', 'normal'); doc.setFontSize(9);
  doc.text('Research', pageW - margin, y, { align: 'right' });
  y += 6;
  doc.setDrawColor(229, 231, 235); doc.line(margin, y, pageW - margin, y); y += 22;

  doc.setTextColor(17, 24, 39); doc.setFont('helvetica', 'bold'); doc.setFontSize(20);
  doc.splitTextToSize(paper.title, contentW).forEach((l) => { ensure(24); doc.text(l, margin, y); y += 24; });
  y += 6;

  doc.setFont('helvetica', 'normal'); doc.setFontSize(12); doc.setTextColor(75, 85, 99);
  doc.text((paper.authors || []).join(', ') || 'Anonymous', margin, y); y += 16;
  const meta = [year, paper.field, paper.citation_id].filter(Boolean).join('  ·  ');
  if (meta) { doc.setFontSize(9); doc.text(meta, margin, y); y += 14; }
  y += 10;

  if (paper.abstract) {
    doc.setFont('helvetica', 'bold'); doc.setFontSize(9); doc.setTextColor(107, 114, 128);
    doc.text('ABSTRACT', margin, y); y += 14;
    doc.setFont('helvetica', 'normal'); doc.setFontSize(11); doc.setTextColor(31, 41, 55);
    doc.splitTextToSize(paper.abstract, contentW).forEach((l) => { ensure(15); doc.text(l, margin, y); y += 15; });
    y += 16;
  }

  const blocks = paper.body ? htmlToBlocks(paper.body) : [];
  blocks.forEach((b) => {
    if (b.type === 'h') {
      const size = b.level <= 1 ? 15 : b.level === 2 ? 13 : 12;
      doc.setFont('helvetica', 'bold'); doc.setFontSize(size); doc.setTextColor(17, 24, 39);
      y += 6;
      doc.splitTextToSize(b.text, contentW).forEach((l) => { ensure(size + 6); doc.text(l, margin, y); y += size + 6; });
      y += 4;
    } else if (b.type === 'quote') {
      doc.setFont('helvetica', 'italic'); doc.setFontSize(11); doc.setTextColor(75, 85, 99);
      doc.splitTextToSize(b.text, contentW - 20).forEach((l) => { ensure(15); doc.text(l, margin + 16, y); y += 15; });
      y += 8;
    } else if (b.type === 'li') {
      doc.setFont('helvetica', 'normal'); doc.setFontSize(11); doc.setTextColor(31, 41, 55);
      const lines = doc.splitTextToSize(`${b.bullet}  ${b.text}`, contentW - 16);
      lines.forEach((l, i) => { ensure(15); doc.text(i === 0 ? l : '    ' + l.trimStart(), margin + 16, y); y += 15; });
      y += 3;
    } else {
      doc.setFont('helvetica', 'normal'); doc.setFontSize(11); doc.setTextColor(31, 41, 55);
      doc.splitTextToSize(b.text, contentW).forEach((l) => { ensure(15); doc.text(l, margin, y); y += 15; });
      y += 6;
    }
  });

  if (paper.references && paper.references.length) {
    y += 8; ensure(20);
    doc.setFont('helvetica', 'bold'); doc.setFontSize(13); doc.setTextColor(17, 24, 39);
    doc.text('References', margin, y); y += 16;
    doc.setFont('helvetica', 'normal'); doc.setFontSize(10); doc.setTextColor(31, 41, 55);
    paper.references.forEach((r, i) => {
      const ref = [r.authors, r.year && `(${r.year})`, r.title, r.source].filter(Boolean).join(' ');
      const lines = doc.splitTextToSize(`${i + 1}. ${ref}`, contentW);
      lines.forEach((l, idx) => { ensure(14); doc.text(l, margin + (idx === 0 ? 0 : 16), y); y += 14; });
      y += 2;
    });
  }

  y += 14; ensure(60);
  doc.setDrawColor(229, 231, 235); doc.line(margin, y, pageW - margin, y); y += 16;
  doc.setFont('helvetica', 'bold'); doc.setFontSize(9); doc.setTextColor(107, 114, 128);
  doc.text('CITE THIS ARTICLE', margin, y); y += 14;
  doc.setFont('helvetica', 'normal'); doc.setFontSize(10); doc.setTextColor(31, 41, 55);
  doc.splitTextToSize(c.apa, contentW).forEach((l) => { ensure(14); doc.text(l, margin, y); y += 14; });
  if (paper.citation_id) {
    doc.setFont('helvetica', 'bold'); doc.setFontSize(9); doc.setTextColor(59, 130, 246);
    doc.text(`Citation ID: ${paper.citation_id}`, margin, y); y += 14;
  }

  doc.save(`${(paper.citation_id || 'paper').replace(/[^a-z0-9-]/gi, '_')}.pdf`);
}
```

---

## `src/lib/publicProfiles.js`

```javascript
import { base44 } from '@/api/base44Client';

// Public author identity (name, avatar, bio) for readers who cannot read User records directly.
const cache = {};

export async function getPublicProfiles(userIds = []) {
  const ids = [...new Set(userIds.filter(Boolean))];
  const missing = ids.filter((id) => !(id in cache));

  if (missing.length) {
    try {
      const res = await base44.functions.invoke('getPublicProfiles', { userIds: missing });
      (res.data?.profiles || []).forEach((p) => { cache[p.id] = p; });
      missing.forEach((id) => { if (!(id in cache)) cache[id] = null; });
    } catch {
      // leave unresolved for a later retry
    }
  }

  const map = {};
  ids.forEach((id) => { if (cache[id]) map[id] = cache[id]; });
  return map;
}

export async function getPublicProfile(userId) {
  if (!userId) return null;
  const map = await getPublicProfiles([userId]);
  return map[userId] || null;
}
```

---

## `src/lib/query-client.js`

```javascript
import { QueryClient } from '@tanstack/react-query';


export const queryClientInstance = new QueryClient({
	defaultOptions: {
		queries: {
			refetchOnWindowFocus: false,
			retry: 1,
		},
	},
});
```

---

## `src/lib/utils.js`

```javascript
import { clsx } from "clsx"
import { twMerge } from "tailwind-merge"

export function cn(...inputs) {
  return twMerge(clsx(inputs))
} 


export const isIframe = window.self !== window.top;

```

---

## `src/main.jsx`

```javascript
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from '@/App.jsx'
import '@/index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <App />
)

```

---

## `src/pages/Admin.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/components/ui/use-toast';
import { Check, X, Ban, RotateCcw, EyeOff, CheckCircle2 } from 'lucide-react';

const call = (action, payload) => base44.functions.invoke('adminAction', { action, payload }).then((r) => r.data);

export default function Admin() {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [tab, setTab] = useState('overview');
  const [manual, setManual] = useState([]);
  const [payouts, setPayouts] = useState([]);
  const [reports, setReports] = useState([]);
  const [stories, setStories] = useState([]);
  const [users, setUsers] = useState([]);
  const [fee, setFee] = useState(20);
  const [bank, setBank] = useState('');
  const [metrics, setMetrics] = useState({ signups: 0, revenue: 0, activeStories: 0 });

  const load = async () => {
    const [mp, po, rp, st, us, feeSet, bankSet, purchases] = await Promise.all([
      base44.entities.ManualPayment.filter({ status: 'pending' }, '-created_date', 50).catch(() => []),
      base44.entities.Payout.filter({ status: 'pending' }, '-created_date', 50).catch(() => []),
      base44.entities.Report.filter({ status: 'open' }, '-created_date', 50).catch(() => []),
      base44.entities.Story.filter({}, '-created_date', 50).catch(() => []),
      base44.entities.User.list().catch(() => []),
      base44.entities.Setting.filter({ key: 'platform_fee_percent' }).catch(() => []),
      base44.entities.Setting.filter({ key: 'bank_instructions' }).catch(() => []),
      base44.entities.Purchase.filter({}, '-created_date', 100).catch(() => []),
    ]);
    const chapterIds = [...new Set(mp.map((m) => m.chapter_id).filter(Boolean))];
    const chapters = chapterIds.length
      ? await base44.entities.Chapter.filter({ id: { $in: chapterIds } }).catch(() => [])
      : [];
    setManual(mp.map((m) => ({ ...m, chapter: chapters.find((c) => c.id === m.chapter_id) || null })));
    setPayouts(po); setReports(rp); setStories(st); setUsers(us);
    if (feeSet[0]) setFee(Number(feeSet[0].value));
    if (bankSet[0]) setBank(bankSet[0].value);
    setMetrics({
      signups: us.length,
      revenue: purchases.reduce((s, p) => s + (p.amount || 0), 0),
      activeStories: st.filter((s) => s.status === 'published').length,
    });
  };

  useEffect(() => { if (user?.role === 'admin') load(); }, [user]);

  const act = async (action, payload, msg) => {
    try {
      await call(action, payload);
      toast({ title: msg });
      load();
    } catch (e) {
      toast({ title: 'Action failed', description: e.message, variant: 'destructive' });
    }
  };

  if (!user) return <p className="text-muted-foreground text-sm">Loading…</p>;
  if (user.role !== 'admin') return <p className="text-muted-foreground text-sm">You don't have access to this page.</p>;

  const tabs = ['overview', 'payments', 'payouts', 'moderation', 'settings'];

  return (
    <div className="space-y-8">
      <h1 className="font-heading text-3xl font-semibold tracking-tight">Admin dashboard</h1>

      <div className="flex gap-1 border-b border-border overflow-x-auto">
        {tabs.map((t) => (
          <button key={t} onClick={() => setTab(t)} className={`px-4 py-2 text-sm capitalize border-b-2 -mb-px whitespace-nowrap ${tab === t ? 'border-foreground font-medium' : 'border-transparent text-muted-foreground'}`}>{t}</button>
        ))}
      </div>

      {tab === 'overview' && (
        <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
          <Metric label="Signups" value={metrics.signups} />
          <Metric label="Revenue" value={`$${metrics.revenue.toFixed(2)}`} />
          <Metric label="Active stories" value={metrics.activeStories} />
          <Metric label="Pending reports" value={reports.length} />
        </div>
      )}

      {tab === 'payments' && (
        <section className="space-y-3">
          <h2 className="font-heading text-xl font-semibold">Manual bank-transfer payments</h2>
          {manual.length === 0 ? <p className="text-sm text-muted-foreground">No pending payments.</p> : manual.map((m) => (
            <div key={m.id} className="flex items-center justify-between rounded-xl border border-border/60 p-4">
              <div>
                <p className="text-sm font-medium">
                  {m.chapter?.title || 'Unknown chapter'} — ${Number(m.chapter?.price || 0).toFixed(2)}
                </p>
                <p className="text-xs text-muted-foreground">
                  Claimed ${Number(m.amount || 0).toFixed(2)} · ref “{m.reference}” · {new Date(m.created_date).toLocaleString()}
                </p>
                {Number(m.chapter?.price || 0) !== Number(m.amount || 0) && (
                  <p className="text-xs text-destructive mt-1">
                    Claimed amount differs from the chapter price — approval records the chapter price.
                  </p>
                )}
              </div>
              <div className="flex gap-2">
                <Button size="sm" className="rounded-full" onClick={() => act('approve_manual', { id: m.id }, 'Payment approved — access granted')}><Check className="w-4 h-4 mr-1.5" /> Approve</Button>
                <Button size="sm" variant="outline" className="rounded-full" onClick={() => act('reject_manual', { id: m.id }, 'Payment rejected')}><X className="w-4 h-4 mr-1.5" /> Reject</Button>
              </div>
            </div>
          ))}
        </section>
      )}

      {tab === 'payouts' && (
        <section className="space-y-3">
          <h2 className="font-heading text-xl font-semibold">Payout requests</h2>
          {payouts.length === 0 ? <p className="text-sm text-muted-foreground">No pending payouts.</p> : payouts.map((p) => (
            <div key={p.id} className="flex items-center justify-between rounded-xl border border-border/60 p-4">
              <div>
                <p className="text-sm font-medium">${p.amount.toFixed(2)} · {p.method}</p>
                <p className="text-xs text-muted-foreground">{new Date(p.created_date).toLocaleString()}</p>
              </div>
              <Button size="sm" className="rounded-full" onClick={() => act('mark_payout_paid', { id: p.id }, 'Payout marked paid')}><CheckCircle2 className="w-4 h-4 mr-1.5" /> Mark paid</Button>
            </div>
          ))}
        </section>
      )}

      {tab === 'moderation' && (
        <div className="space-y-8">
          <section className="space-y-3">
            <h2 className="font-heading text-xl font-semibold">Open reports</h2>
            {reports.length === 0 ? <p className="text-sm text-muted-foreground">No open reports.</p> : reports.map((r) => (
              <div key={r.id} className="flex items-center justify-between rounded-xl border border-border/60 p-4">
                <div>
                  <p className="text-sm">{r.reason}</p>
                  <p className="text-xs text-muted-foreground">{r.target_type} · {new Date(r.created_date).toLocaleString()}</p>
                </div>
                <Button size="sm" variant="outline" className="rounded-full" onClick={() => act('resolve_report', { id: r.id }, 'Report resolved')}>Resolve</Button>
              </div>
            ))}
          </section>
          <section className="space-y-3">
            <h2 className="font-heading text-xl font-semibold">Stories</h2>
            {stories.map((s) => (
              <div key={s.id} className="flex items-center justify-between rounded-xl border border-border/60 p-4">
                <div>
                  <p className="text-sm font-medium">{s.title}</p>
                  <p className="text-xs text-muted-foreground">{s.status} · {s.genre}</p>
                </div>
                {s.status === 'published' && <Button size="sm" variant="outline" className="rounded-full" onClick={() => act('unpublish_story', { id: s.id }, 'Story unpublished')}><EyeOff className="w-4 h-4 mr-1.5" /> Unpublish</Button>}
              </div>
            ))}
          </section>
          <section className="space-y-3">
            <h2 className="font-heading text-xl font-semibold">Users</h2>
            {users.map((u) => (
              <div key={u.id} className="flex items-center justify-between rounded-xl border border-border/60 p-4">
                <div>
                  <p className="text-sm font-medium">{u.display_name || u.full_name || u.email}</p>
                  <p className="text-xs text-muted-foreground">{u.role}{u.suspended ? ' · suspended' : ''}</p>
                </div>
                {u.suspended ? (
                  <Button size="sm" variant="outline" className="rounded-full" onClick={() => act('reinstate_user', { id: u.id }, 'User reinstated')}><RotateCcw className="w-4 h-4 mr-1.5" /> Reinstate</Button>
                ) : (
                  <Button size="sm" variant="outline" className="rounded-full" onClick={() => act('suspend_user', { id: u.id }, 'User suspended')}><Ban className="w-4 h-4 mr-1.5" /> Suspend</Button>
                )}
              </div>
            ))}
          </section>
        </div>
      )}

      {tab === 'settings' && (
        <div className="space-y-8 max-w-lg">
          <section className="space-y-3">
            <h2 className="font-heading text-xl font-semibold">Platform fee</h2>
            <p className="text-sm text-muted-foreground">The platform keeps this percentage of each payment; the writer receives the rest.</p>
            <div className="flex items-center gap-2">
              <Input type="number" min="0" max="100" value={fee} onChange={(e) => setFee(e.target.value)} className="w-24" />
              <span className="text-sm text-muted-foreground">%</span>
              <Button className="rounded-full" onClick={() => act('set_fee', { value: fee }, 'Fee updated')}>Save</Button>
            </div>
            <p className="text-xs text-muted-foreground">Current split: writer {100 - Number(fee)}% / platform {Number(fee)}%</p>
          </section>
          <section className="space-y-3">
            <h2 className="font-heading text-xl font-semibold">Bank transfer instructions</h2>
            <p className="text-sm text-muted-foreground">Shown to readers who choose the bank-transfer payment option.</p>
            <Textarea value={bank} onChange={(e) => setBank(e.target.value)} rows={4} placeholder="Bank name, account holder, account number, etc." />
            <Button className="rounded-full" onClick={() => act('set_bank', { value: bank }, 'Bank details updated')}>Save</Button>
          </section>
        </div>
      )}
    </div>
  );
}

function Metric({ label, value }) {
  return (
    <div className="rounded-xl border border-border/60 p-4">
      <p className="text-xs text-muted-foreground">{label}</p>
      <p className="font-heading text-2xl font-semibold mt-1">{value}</p>
    </div>
  );
}
```

---

## `src/pages/AppSource.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { useSeo } from '@/hooks/useSeo';
import { Check, Copy, Download, FileCode2, Layers, Loader2, Server } from 'lucide-react';

const SOURCE_URL = '/chapterly-source.md';
const FILE_NAME = 'chapterly-app-source.md';

export default function AppSource() {
  useSeo({
    title: 'App source — Chapterly',
    description: 'Download or copy the complete Chapterly codebase as a single file.',
  });

  const { toast } = useToast();
  const [text, setText] = useState(null);
  const [copied, setCopied] = useState(false);
  const [copying, setCopying] = useState(false);

  useEffect(() => {
    let active = true;
    fetch(SOURCE_URL)
      .then((r) => r.text())
      .then((t) => active && setText(t))
      .catch(() => active && setText(''))
      .finally(() => {});
    return () => { active = false; };
  }, []);

  const stats = (() => {
    if (!text) return null;
    return {
      kb: Math.round(new Blob([text]).size / 1024),
      lines: text.split('\n').length,
      files: (text.match(/^## `/gm) || []).length,
    };
  })();

  const copy = async () => {
    if (!text) return;
    setCopying(true);
    try {
      await navigator.clipboard.writeText(text);
      setCopied(true);
      setTimeout(() => setCopied(false), 2500);
      toast({ title: 'Copied to clipboard', description: 'The whole app source is ready to paste.' });
    } catch {
      toast({
        title: 'Could not copy',
        description: 'Use the download button, then copy from the file.',
        variant: 'destructive',
      });
    } finally {
      setCopying(false);
    }
  };

  return (
    <div className="max-w-3xl mx-auto space-y-8">
      <div>
        <h1 className="font-heading text-3xl font-semibold tracking-tight">App source</h1>
        <p className="text-sm text-muted-foreground mt-1.5 max-w-lg">
          The entire Chapterly codebase — frontend, entities, backend functions, agents and workflows —
          bundled into one file you can download or copy in a single click.
        </p>
      </div>

      <div className="rounded-2xl border border-border/60 bg-card p-5 space-y-5">
        <div className="flex flex-wrap items-center gap-3">
          <Button asChild size="lg" className="rounded-full">
            <a href={SOURCE_URL} download={FILE_NAME}>
              <Download className="w-4 h-4" /> Download the single file
            </a>
          </Button>
          <Button
            onClick={copy}
            variant="outline"
            size="lg"
            className="rounded-full"
            disabled={!text || copying}
          >
            {copying ? (
              <Loader2 className="w-4 h-4 animate-spin" />
            ) : copied ? (
              <Check className="w-4 h-4" />
            ) : (
              <Copy className="w-4 h-4" />
            )}
            {copied ? 'Copied' : 'Copy all code'}
          </Button>
        </div>

        <div className="grid grid-cols-3 gap-3 text-center">
          <div className="rounded-xl bg-muted/60 px-3 py-3">
            <p className="font-heading text-lg font-semibold">{stats ? stats.files : '—'}</p>
            <p className="text-[11px] text-muted-foreground">files</p>
          </div>
          <div className="rounded-xl bg-muted/60 px-3 py-3">
            <p className="font-heading text-lg font-semibold">{stats ? stats.lines.toLocaleString() : '—'}</p>
            <p className="text-[11px] text-muted-foreground">lines</p>
          </div>
          <div className="rounded-xl bg-muted/60 px-3 py-3">
            <p className="font-heading text-lg font-semibold">{stats ? `${stats.kb} KB` : '—'}</p>
            <p className="text-[11px] text-muted-foreground">size</p>
          </div>
        </div>

        <p className="text-xs text-muted-foreground">
          Every file keeps its exact path with a heading and a code block, so the project can be rebuilt
          file by file. This snapshot is the source code itself — the running app is this project.
        </p>
      </div>

      <div className="space-y-3">
        <h2 className="font-heading text-lg font-semibold">What's inside</h2>
        <ul className="space-y-2.5 text-sm">
          <li className="flex items-start gap-2.5">
            <Layers className="w-4 h-4 mt-0.5 text-muted-foreground shrink-0" />
            <span><span className="font-medium">Frontend</span> — every page and component, the router and the design tokens.</span>
          </li>
          <li className="flex items-start gap-2.5">
            <FileCode2 className="w-4 h-4 mt-0.5 text-muted-foreground shrink-0" />
            <span><span className="font-medium">Data model</span> — all entity schemas with their access rules.</span>
          </li>
          <li className="flex items-start gap-2.5">
            <Server className="w-4 h-4 mt-0.5 text-muted-foreground shrink-0" />
            <span><span className="font-medium">Backend</span> — functions, shared helpers, AI agents and workflows, plus project config.</span>
          </li>
        </ul>
      </div>
    </div>
  );
}
```

---

## `src/pages/Assistant.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, Bot } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function Assistant() {
  const { user } = useCurrentUser();
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'Chapterly Assistant', description: 'Ask the Chapterly Assistant anything about stories, chapters, research, your library, and more.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const convs = await base44.agents.listConversations({ agent_name: 'chapterly_assistant' });
        let conv = (convs || []).find((c) => c.metadata?.user_key === user.id);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'chapterly_assistant',
            metadata: { user_key: user.id, name: 'Chapterly Assistant' },
          });
          await base44.agents.addMessage(conv, { role: 'user', content: 'Hi! I am here. What can you help me with on Chapterly?' });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setConversation(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <Bot className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">Chapterly Assistant</h1>
        <p className="text-sm text-muted-foreground">Sign in to chat with the Chapterly Assistant about stories, your library, earnings, and more.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to="/" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Home
      </Link>

      <div className="flex items-center gap-2">
        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
          <Bot className="w-5 h-5 text-primary" />
        </div>
        <div>
          <h1 className="font-heading text-xl font-semibold">Chapterly Assistant</h1>
          <p className="text-sm text-muted-foreground">Ask about stories, chapters, research, your library, earnings, and more</p>
        </div>
      </div>

      <div ref={scrollRef} className="h-[60vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Starting your assistant…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Ask anything to get started.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask the Chapterly Assistant…"
          rows={2}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/Browse.jsx`

```javascript
import { useEffect, useState, useMemo } from 'react';
import { base44 } from '@/api/base44Client';
import StoryCard from '@/components/StoryCard';
import PullToRefresh from '@/components/PullToRefresh';
import { Input } from '@/components/ui/input';
import { Search, Flame, Clock, Plus } from 'lucide-react';
import { useSeo } from '@/hooks/useSeo';
import GenreDialog from '@/components/genre/GenreDialog';
import { loadGenres, subGenreNames, topLevelNames } from '@/lib/genres';

export default function Browse() {
  const [stories, setStories] = useState([]);
  const [likes, setLikes] = useState({});
  const [genre, setGenre] = useState('All');
  const [q, setQ] = useState('');
  const [tag, setTag] = useState(null);
  const [sort, setSort] = useState('trending');
  const [genres, setGenres] = useState([]);
  const [sub, setSub] = useState(null);
  const [genreDialog, setGenreDialog] = useState(false);

  useSeo({
    title: genre === 'All' ? 'Browse serials — Chapterly' : `Browse ${genre} serials — Chapterly`,
    description:
      genre === 'All'
        ? 'Browse trending and new serialized fiction on Chapterly — fantasy, romance, mystery, sci-fi and more. Read the first chapters free.'
        : `Browse ${genre} serialized fiction on Chapterly — discover indie writers, read chapter by chapter, and follow your favorites.`,
    url: '/browse',
    jsonLd: {
      '@context': 'https://schema.org',
      '@type': 'CollectionPage',
      name: genre === 'All' ? 'Browse serials on Chapterly' : `Browse ${genre} serials on Chapterly`,
      url: 'https://chapterly.ariamalik.com/browse',
    },
  });

  const loadData = () =>
    Promise.all([
      base44.entities.Story.filter({ status: 'published' }, '-created_date', 60),
      base44.entities.Like.filter({ target_type: 'story' }),
      loadGenres().catch(() => []),
    ]).then(([s, all, gs]) => {
      setStories(s);
      setGenres(gs);
      const map = {};
      all.forEach((l) => { map[l.target_id] = (map[l.target_id] || 0) + 1; });
      setLikes(map);
    });

  useEffect(() => {
    loadData().catch(() => {});
  }, []);

  const tags = useMemo(() => {
    const counts = {};
    stories.forEach((s) => (s.tags || []).forEach((t) => { counts[t] = (counts[t] || 0) + 1; }));
    return Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, 12).map(([t]) => t);
  }, [stories]);

  const genreNames = useMemo(() => {
    const known = topLevelNames(genres);
    const fromStories = stories.map((s) => s.genre).filter(Boolean);
    return [...new Set([...known, ...fromStories])];
  }, [genres, stories]);

  const subNames = useMemo(() => {
    if (genre === 'All') return [];
    const known = subGenreNames(genres, genre);
    const fromStories = stories.filter((s) => s.genre === genre).map((s) => s.sub_genre).filter(Boolean);
    return [...new Set([...known, ...fromStories])];
  }, [genres, stories, genre]);

  const filtered = useMemo(() => {
    const query = q.toLowerCase().trim();
    let list = stories.filter((s) => {
      const matchGenre = genre === 'All' || s.genre === genre;
      const matchSub = !sub || s.sub_genre === sub;
      const matchTag = !tag || (s.tags || []).includes(tag);
      const matchQuery =
        !query ||
        s.title.toLowerCase().includes(query) ||
        (s.tags || []).some((t) => t.toLowerCase().includes(query));
      return matchGenre && matchSub && matchTag && matchQuery;
    });
    if (sort === 'trending') {
      list = [...list].sort((a, b) => (likes[b.id] || 0) - (likes[a.id] || 0));
    }
    return list;
  }, [stories, genre, sub, q, tag, sort, likes]);

  return (
    <PullToRefresh onRefresh={loadData}>
    <div className="space-y-8">
      <div>
        <h1 className="font-heading text-3xl font-semibold tracking-tight">Browse</h1>
        <div className="mt-4 relative max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search by title or tag"
            className="pl-9 rounded-full"
          />
        </div>
      </div>

      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div className="flex flex-wrap gap-2">
          {['All', ...genreNames].map((g) => (
            <button
              key={g}
              onClick={() => { setGenre(g); setSub(null); }}
              className={`px-3.5 py-1.5 rounded-full text-sm transition ${
                genre === g
                  ? 'bg-foreground text-background'
                  : 'border border-border text-muted-foreground hover:text-foreground hover:bg-muted'
              }`}
            >
              {g}
            </button>
          ))}
          <button
            onClick={() => setGenreDialog(true)}
            className="px-3.5 py-1.5 rounded-full text-sm border border-dashed border-border text-muted-foreground hover:text-foreground hover:bg-muted transition inline-flex items-center gap-1"
          >
            <Plus className="w-3.5 h-3.5" /> New genre
          </button>
        </div>
        <div className="flex items-center gap-1.5 rounded-full border border-border p-0.5">
          <button
            onClick={() => setSort('trending')}
            className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition ${
              sort === 'trending' ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <Flame className="w-3.5 h-3.5" /> Trending
          </button>
          <button
            onClick={() => setSort('latest')}
            className={`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs font-medium transition ${
              sort === 'latest' ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground'
            }`}
          >
            <Clock className="w-3.5 h-3.5" /> Latest
          </button>
        </div>
      </div>

      {genre !== 'All' && (
        <div className="flex flex-wrap items-center gap-2">
          <span className="text-xs text-muted-foreground">Sub-categories:</span>
          <button
            onClick={() => setSub(null)}
            className={`text-xs px-2.5 py-1 rounded-full transition ${
              !sub ? 'bg-muted text-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
            }`}
          >
            All
          </button>
          {subNames.map((s) => (
            <button
              key={s}
              onClick={() => setSub(sub === s ? null : s)}
              className={`text-xs px-2.5 py-1 rounded-full transition ${
                sub === s ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
              }`}
            >
              {s}
            </button>
          ))}
          <button
            onClick={() => setGenreDialog(true)}
            className="text-xs px-2.5 py-1 rounded-full border border-dashed border-border text-muted-foreground hover:text-foreground hover:bg-muted transition inline-flex items-center gap-1"
          >
            <Plus className="w-3 h-3" /> New sub-category
          </button>
        </div>
      )}

      {tags.length > 0 && (
        <div className="flex flex-wrap gap-2">
          <button
            onClick={() => setTag(null)}
            className={`text-xs px-2.5 py-1 rounded-full transition ${
              !tag ? 'bg-muted text-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
            }`}
          >
            All tags
          </button>
          {tags.map((t) => (
            <button
              key={t}
              onClick={() => setTag(tag === t ? null : t)}
              className={`text-xs px-2.5 py-1 rounded-full transition ${
                tag === t ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
              }`}
            >
              #{t}
            </button>
          ))}
        </div>
      )}

      {filtered.length === 0 ? (
        <p className="text-muted-foreground text-sm">No stories match your search.</p>
      ) : (
        <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-5">
          {filtered.map((s) => (
            <StoryCard key={s.id} story={s} likeCount={likes[s.id] || 0} />
          ))}
        </div>
      )}
      <GenreDialog
        open={genreDialog}
        onOpenChange={setGenreDialog}
        defaultParentName={genre === 'All' ? '' : genre}
        onCreated={() => loadData().catch(() => {})}
      />
    </div>
    </PullToRefresh>
  );
}
```

---

## `src/pages/ChapterEditor.jsx`

```javascript
import { useEffect, useState, useRef } from 'react';
import { useParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
import RichTextEditor from '@/components/RichTextEditor';
import AIAssistantPanel from '@/components/AIAssistantPanel';
import { ArrowLeft, Check, Lock, Eye, EyeOff, CalendarClock } from 'lucide-react';

function countWords(html) {
  const text = (html || '').replace(/<[^>]+>/g, ' ').trim();
  return text ? text.split(/\s+/).length : 0;
}

export default function ChapterEditor() {
  const { storyId, chapterId } = useParams();
  const { toast } = useToast();
  const [chapter, setChapter] = useState(null);
  const [saving, setSaving] = useState(false);
  const [savedAt, setSavedAt] = useState(null);
  const timer = useRef(null);
  const [releaseDate, setReleaseDate] = useState('');

  useEffect(() => {
    if (!chapter?.release_date) { setReleaseDate(''); return; }
    const d = new Date(chapter.release_date);
    if (isNaN(d.getTime())) { setReleaseDate(''); return; }
    const off = d.getTimezoneOffset();
    setReleaseDate(new Date(d.getTime() - off * 60000).toISOString().slice(0, 16));
  }, [chapter?.release_date]);

  useEffect(() => {
    let active = true;
    (async () => {
      if (chapterId === 'new') {
        const order = (await base44.entities.Chapter.filter({ story_id: storyId })).length;
        const c = await base44.entities.Chapter.create({ story_id: storyId, title: 'Untitled chapter', body: '', status: 'free', price: 0, published: false, order_index: order });
        if (active) setChapter(c);
        window.history.replaceState({}, '', `/dashboard/story/${storyId}/chapter/${c.id}`);
      } else {
        const c = await base44.entities.Chapter.get(chapterId);
        // Paid bodies live in ChapterContent; the writer and admins get them back through the backend
        let body = c.body || '';
        if (!body && c.status === 'paid') {
          const res = await base44.functions.invoke('getChapterContent', { chapterId: c.id }).catch(() => null);
          body = res?.data?.body || '';
        }
        if (active) setChapter({ ...c, body });
      }
    })();
    return () => { active = false; };
  }, [storyId, chapterId]);

  const autosave = (patch) => {
    setChapter((c) => ({ ...c, ...patch }));
    if (timer.current) clearTimeout(timer.current);
    timer.current = setTimeout(async () => {
      setSaving(true);
      try {
        const next = { ...chapter, ...patch };
        const nextBody = next.body || '';
        if (next.status === 'paid') {
          // Keep paid content out of the publicly readable Chapter record
          const existing = await base44.entities.ChapterContent.filter({ chapter_id: chapter.id });
          if (existing[0]) await base44.entities.ChapterContent.update(existing[0].id, { body: nextBody });
          else await base44.entities.ChapterContent.create({ chapter_id: chapter.id, story_id: chapter.story_id, writer_id: chapter.created_by_id, body: nextBody });
        }
        await base44.entities.Chapter.update(chapter.id, {
          title: next.title,
          body: next.status === 'paid' ? '' : nextBody,
          status: next.status,
          price: next.price,
          word_count: countWords(nextBody),
        });
        setSavedAt(new Date());
      } catch {
        toast({ title: 'Autosave failed', variant: 'destructive' });
      }
      setSaving(false);
    }, 1200);
  };

  const appendText = (html) => {
    const next = (chapter.body || '') + html;
    autosave({ body: next });
  };

  const fromLocalInput = (val) => (val ? new Date(val).toISOString() : null);

  const scheduleRelease = async () => {
    const iso = fromLocalInput(releaseDate);
    if (!iso) return toast({ title: 'Pick a date and time', variant: 'destructive' });
    if (new Date(iso) <= new Date()) return toast({ title: 'Choose a future date', variant: 'destructive' });
    try {
      await base44.entities.Chapter.update(chapter.id, { release_date: iso, published: false, word_count: countWords(chapter.body) });
      setChapter({ ...chapter, release_date: iso, published: false });
      toast({ title: 'Chapter scheduled', description: new Date(iso).toLocaleString() });
    } catch (e) {
      toast({ title: 'Scheduling failed', description: e.message, variant: 'destructive' });
    }
  };

  const cancelSchedule = async () => {
    try {
      await base44.entities.Chapter.update(chapter.id, { release_date: null });
      setChapter({ ...chapter, release_date: null });
      setReleaseDate('');
      toast({ title: 'Schedule cleared' });
    } catch (e) {
      toast({ title: 'Could not clear schedule', description: e.message, variant: 'destructive' });
    }
  };

  if (!chapter) return <p className="text-muted-foreground text-sm">Loading editor…</p>;

  return (
    <div className="space-y-6">
      <Link to={`/dashboard/story/${storyId}`} className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Back to story
      </Link>

      <div className="flex items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          <h1 className="font-heading text-2xl font-semibold">Chapter editor</h1>
          <span className="text-xs text-muted-foreground">
            {saving ? 'Saving…' : savedAt ? 'All changes saved' : ''}
          </span>
        </div>
        <Button
          onClick={async () => {
            const goingLive = !chapter.published;
            await base44.entities.Chapter.update(chapter.id, { published: goingLive, release_date: goingLive ? null : (chapter.release_date || null), word_count: countWords(chapter.body) });
            setChapter({ ...chapter, published: goingLive, release_date: goingLive ? null : chapter.release_date });
            toast({ title: goingLive ? 'Published — followers will be notified' : 'Unpublished' });
          }}
          variant={chapter.published ? 'default' : 'outline'}
          className="rounded-full"
        >
          {chapter.published ? <EyeOff className="w-4 h-4 mr-1.5" /> : <Eye className="w-4 h-4 mr-1.5" />}
          {chapter.published ? 'Unpublish' : 'Publish'}
        </Button>
      </div>

      <div>
        <Label>Chapter title</Label>
        <Input
          value={chapter.title}
          onChange={(e) => { setChapter({ ...chapter, title: e.target.value }); autosave({ title: e.target.value }); }}
          className="mt-1.5 text-lg"
          placeholder="Chapter 1 — The Beginning"
        />
      </div>

      <div className="flex flex-wrap items-center gap-4">
        <div className="flex items-center gap-2">
          <Label className="mb-0">Access</Label>
          <div className="flex rounded-full border border-border overflow-hidden">
            <button
              onClick={() => autosave({ status: 'free', price: 0 })}
              className={`px-3.5 py-1.5 text-sm ${chapter.status === 'free' ? 'bg-foreground text-background' : ''}`}
            >
              Free
            </button>
            <button
              onClick={() => autosave({ status: 'paid', price: chapter.price || 0.49 })}
              className={`px-3.5 py-1.5 text-sm flex items-center gap-1.5 ${chapter.status === 'paid' ? 'bg-foreground text-background' : ''}`}
            >
              <Lock className="w-3.5 h-3.5" /> Paid
            </button>
          </div>
        </div>
        {chapter.status === 'paid' && (
          <div className="flex items-center gap-2">
            <Label className="mb-0">Price ($)</Label>
            <Input
              type="number"
              min="0.49"
              max="9.99"
              step="0.01"
              value={chapter.price ?? 0}
              onChange={(e) => autosave({ price: parseFloat(e.target.value) })}
              className="w-24"
            />
          </div>
        )}
        <span className="text-xs text-muted-foreground">{countWords(chapter.body)} words</span>
      </div>

      <div className="rounded-xl border border-border/60 p-4 space-y-3">
        <div className="flex items-center gap-2">
          <CalendarClock className="w-4 h-4" />
          <h3 className="font-heading text-sm font-semibold">Schedule release</h3>
        </div>
        {chapter.release_date && new Date(chapter.release_date) > new Date() ? (
          <div className="flex flex-wrap items-center justify-between gap-3">
            <p className="text-sm text-muted-foreground">
              Scheduled to go live on <span className="font-medium text-foreground">{new Date(chapter.release_date).toLocaleString()}</span>
            </p>
            <Button variant="outline" size="sm" className="rounded-full" onClick={cancelSchedule}>Cancel schedule</Button>
          </div>
        ) : (
          <div className="flex flex-wrap items-end gap-3">
            <div>
              <Label className="text-xs">Release date &amp; time</Label>
              <input
                type="datetime-local"
                value={releaseDate}
                onChange={(e) => setReleaseDate(e.target.value)}
                className="mt-1.5 flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
              />
            </div>
            <Button variant="outline" size="sm" className="rounded-full" onClick={scheduleRelease}>
              <CalendarClock className="w-3.5 h-3.5 mr-1" /> Schedule
            </Button>
            <p className="text-xs text-muted-foreground basis-full">The chapter stays hidden until this time, then publishes automatically.</p>
          </div>
        )}
      </div>

      <div>
        <Label>Body</Label>
        <div className="mt-1.5">
          <RichTextEditor value={chapter.body} onChange={(v) => autosave({ body: v })} placeholder="Start writing your chapter…" />
        </div>
      </div>

      <AIAssistantPanel body={chapter.body} title={chapter.title} onInsert={appendText} />
    </div>
  );
}
```

---

## `src/pages/ChapterEngagementReport.jsx`

```javascript
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { ArrowLeft, Eye, MessageSquare, Unlock, Coins, BarChart3, Trophy, BookOpenCheck, Sparkles } from 'lucide-react';
import { useSeo } from '@/hooks/useSeo';

const SORTS = [
  { key: 'score', label: 'Engagement' },
  { key: 'full_reads', label: 'Full reads' },
  { key: 'views', label: 'Views' },
  { key: 'comments', label: 'Comments' },
  { key: 'tips', label: 'Tips' },
  { key: 'unlocks', label: 'Unlocks' },
];

export default function ChapterEngagementReport() {
  const { user } = useCurrentUser();
  const [rows, setRows] = useState([]);
  const [totals, setTotals] = useState({ reads: 0, fullReads: 0, comments: 0, unlocks: 0, tips: 0, tipAmount: 0 });
  const [loading, setLoading] = useState(true);
  const [sort, setSort] = useState('score');

  useSeo({ title: 'Chapter Engagement Report — Chapterly', description: 'See which of your chapters drive the most reads, comments, tips, and unlocks.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const stories = await base44.entities.Story.filter({ created_by_id: user.id });
        if (stories.length === 0) { if (active) { setRows([]); setLoading(false); } return; }
        const storyIds = stories.map((s) => s.id);
        const storyMap = Object.fromEntries(stories.map((s) => [s.id, s]));

        const chapters = await base44.entities.Chapter.filter({ story_id: { $in: storyIds } });
        const chapterIds = chapters.map((c) => c.id);

        const [purchases, comments, tips] = await Promise.all([
          base44.entities.Purchase.filter({ writer_id: user.id }).catch(() => []),
          chapterIds.length ? base44.entities.Comment.filter({ chapter_id: { $in: chapterIds } }) : Promise.resolve([]),
          base44.entities.Tip.filter({ writer_id: user.id }).catch(() => []),
        ]);

        const commentCount = {};
        (comments || []).forEach((c) => { commentCount[c.chapter_id] = (commentCount[c.chapter_id] || 0) + 1; });
        const unlockCount = {};
        (purchases || []).forEach((p) => { if (p.chapter_id) unlockCount[p.chapter_id] = (unlockCount[p.chapter_id] || 0) + 1; });
        const tipCount = {};
        const tipAmount = {};
        (tips || []).forEach((t) => {
          if (!t.chapter_id) return;
          tipCount[t.chapter_id] = (tipCount[t.chapter_id] || 0) + 1;
          tipAmount[t.chapter_id] = (tipAmount[t.chapter_id] || 0) + (t.amount || 0);
        });

        const built = chapters.map((c) => {
          const views = c.views || 0;
          const fullReads = c.full_reads || 0;
          const comments_n = commentCount[c.id] || 0;
          const unlocks = unlockCount[c.id] || 0;
          const tips_n = tipCount[c.id] || 0;
          const tipsAmt = tipAmount[c.id] || 0;
          // weighted engagement: completions & paid signals outweigh raw views
          const score = views + fullReads * 3 + comments_n * 5 + unlocks * 8 + tips_n * 12;
          return {
            id: c.id,
            title: c.title,
            order: c.order_index || 0,
            storyId: c.story_id,
            storyTitle: storyMap[c.story_id]?.title || 'Untitled',
            published: c.published,
            views,
            full_reads: fullReads,
            comments: comments_n,
            unlocks,
            tips: tips_n,
            tipAmount: tipsAmt,
            score,
          };
        });

        if (active) {
          setRows(built);
          setTotals({
            reads: built.reduce((s, r) => s + r.views, 0),
            fullReads: built.reduce((s, r) => s + r.full_reads, 0),
            comments: built.reduce((s, r) => s + r.comments, 0),
            unlocks: built.reduce((s, r) => s + r.unlocks, 0),
            tips: built.reduce((s, r) => s + r.tips, 0),
            tipAmount: built.reduce((s, r) => s + r.tipAmount, 0),
          });
        }
      } catch {
        if (active) setRows([]);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  const sorted = useMemo(() => [...rows].sort((a, b) => (b[sort] || 0) - (a[sort] || 0)), [rows, sort]);
  const maxScore = Math.max(1, ...sorted.map((r) => r.score || 0));

  const topChapter = sorted[0];
  const insight = topChapter
    ? `“${topChapter.title}” is your strongest chapter — ${topChapter.full_reads} full read${topChapter.full_reads === 1 ? '' : 's'}, ${topChapter.comments} comment${topChapter.comments === 1 ? '' : 's'}, and $${topChapter.tipAmount.toFixed(2)} in tips.`
    : null;

  return (
    <div className="max-w-4xl mx-auto space-y-6">
      <Link to="/dashboard" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Dashboard
      </Link>

      <div className="flex items-center gap-2">
        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
          <BarChart3 className="w-5 h-5 text-primary" />
        </div>
        <div>
          <h1 className="font-heading text-xl font-semibold">Chapter engagement</h1>
          <p className="text-sm text-muted-foreground">Exactly what drives your audience — full reads, comments, tips, and unlocks per chapter.</p>
        </div>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-3 gap-3">
        <StatCard icon={Eye} label="Total views" value={totals.reads} />
        <StatCard icon={BookOpenCheck} label="Full reads" value={totals.fullReads} />
        <StatCard icon={MessageSquare} label="Comments" value={totals.comments} />
        <StatCard icon={Unlock} label="Unlocks" value={totals.unlocks} />
        <StatCard icon={Coins} label="Tips" value={totals.tips} />
        <StatCard icon={Coins} label="Tip revenue" value={`$${totals.tipAmount.toFixed(2)}`} />
      </div>

      {insight && (
        <div className="flex items-start gap-2 rounded-xl border border-primary/30 bg-primary/5 p-4">
          <Sparkles className="w-4 h-4 text-primary mt-0.5 shrink-0" />
          <p className="text-sm text-foreground/80">{insight}</p>
        </div>
      )}

      <div className="flex items-center gap-2 flex-wrap">
        <span className="text-sm text-muted-foreground">Sort by:</span>
        {SORTS.map((s) => (
          <Button
            key={s.key}
            size="sm"
            variant={sort === s.key ? 'default' : 'outline'}
            className="rounded-full"
            onClick={() => setSort(s.key)}
          >
            {s.label}
          </Button>
        ))}
      </div>

      {loading ? (
        <p className="text-sm text-muted-foreground text-center py-12">Crunching the numbers…</p>
      ) : sorted.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-border p-12 text-center">
          <BarChart3 className="w-8 h-8 mx-auto text-muted-foreground" />
          <p className="mt-3 text-sm text-muted-foreground">No chapters to report on yet. Publish a chapter to see engagement.</p>
          <Link to="/dashboard"><Button className="rounded-full mt-4">Go to dashboard</Button></Link>
        </div>
      ) : (
        <div className="space-y-2">
          {sorted.map((r, i) => (
            <div key={r.id} className="p-4 rounded-xl border border-border/60 bg-card">
              <div className="flex items-start gap-3">
                <div className="flex flex-col items-center justify-center w-8 shrink-0">
                  {i < 3 && sort === 'score' ? (
                    <Trophy className={`w-5 h-5 ${i === 0 ? 'text-amber-500' : i === 1 ? 'text-slate-400' : 'text-amber-700'}`} />
                  ) : (
                    <span className="text-sm font-semibold text-muted-foreground">{i + 1}</span>
                  )}
                </div>
                <div className="flex-1 min-w-0">
                  <Link to={`/read/${r.id}`} className="font-heading font-semibold hover:underline truncate block">
                    {r.title || 'Untitled chapter'}
                  </Link>
                  <Link to={`/story/${r.storyId}`} className="text-xs text-muted-foreground hover:underline">
                    {r.storyTitle}
                  </Link>
                  <div className="mt-2 h-1.5 rounded-full bg-muted overflow-hidden">
                    <div className="h-full bg-primary rounded-full" style={{ width: `${(r.score / maxScore) * 100}%` }} />
                  </div>
                </div>
                <div className="flex items-center gap-3 sm:gap-4 text-sm shrink-0 flex-wrap justify-end">
                  <Metric icon={Eye} value={r.views} title="Views" />
                  <Metric icon={BookOpenCheck} value={r.full_reads} title="Full reads" />
                  <Metric icon={MessageSquare} value={r.comments} title="Comments" />
                  <Metric icon={Coins} value={r.tips} title="Tips" />
                  <Metric icon={Unlock} value={r.unlocks} title="Unlocks" />
                </div>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function StatCard({ icon: Icon, label, value }) {
  return (
    <div className="p-4 rounded-xl border border-border/60 bg-card">
      <div className="flex items-center gap-2 text-muted-foreground">
        <Icon className="w-4 h-4" />
        <span className="text-xs">{label}</span>
      </div>
      <p className="mt-1 text-2xl font-heading font-semibold">{value}</p>
    </div>
  );
}

function Metric({ icon: Icon, value, title }) {
  return (
    <span className="flex items-center gap-1.5 text-muted-foreground" title={title}>
      <Icon className="w-4 h-4" />
      <span className="font-medium text-foreground">{value}</span>
    </span>
  );
}
```

---

## `src/pages/CitationExplainer.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, Quote } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function CitationExplainer() {
  const { user } = useCurrentUser();
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'Citation Explainer — Chapterly', description: 'Understand the academic citations connected to research papers mentioned within a story.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const convs = await base44.agents.listConversations({ agent_name: 'citation_explainer' });
        let conv = (convs || []).find((c) => c.metadata?.user_key === user.id);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'citation_explainer',
            metadata: { user_key: user.id, name: 'Citation Explainer' },
          });
          await base44.agents.addMessage(conv, { role: 'user', content: 'Hi! Can you explain the citations linked to research papers mentioned in my stories?' });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setConversation(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <Quote className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">Citation Explainer</h1>
        <p className="text-sm text-muted-foreground">Sign in to explore the academic citations connected to research papers in your stories.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to="/research" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Research
      </Link>

      <div className="flex items-center gap-2">
        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
          <Quote className="w-5 h-5 text-primary" />
        </div>
        <div>
          <h1 className="font-heading text-xl font-semibold">Citation Explainer</h1>
          <p className="text-sm text-muted-foreground">Citations linked to research papers mentioned within a story</p>
        </div>
      </div>

      <div ref={scrollRef} className="h-[60vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Starting your assistant…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Ask about a story to explore its citations.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask about citations in a story…"
          rows={2}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/Connect.jsx`

```javascript
import { Plug, RefreshCw, ShieldCheck } from 'lucide-react';
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
import CopyUrlField from '@/components/connect/CopyUrlField';
import ClientSetup from '@/components/connect/ClientSetup';

const CLIENTS = [
  { id: 'claude', label: 'Claude' },
  { id: 'chatgpt', label: 'ChatGPT' },
  { id: 'cursor', label: 'Cursor' },
  { id: 'others', label: 'Others' },
];

export default function Connect() {
  // Resolved at runtime so the address is always the one serving this page.
  const serverUrl = new URL('/api/mcp', window.location.origin).toString();

  return (
    <div className="mx-auto max-w-3xl">
      <div className="mb-8">
        <div className="mb-3 flex items-center gap-3">
          <span className="flex h-10 w-10 items-center justify-center rounded-xl bg-primary/15">
            <Plug className="h-5 w-5 text-primary" />
          </span>
          <h1 className="font-heading text-2xl font-semibold tracking-tight">
            Connect an assistant
          </h1>
        </div>
        <p className="text-sm text-muted-foreground leading-relaxed">
          Point ChatGPT, Claude, or Cursor at Chapterly and ask it about stories, chapters, and
          authors in plain language. Add this address once and it works from every conversation.
        </p>
      </div>

      <div className="mb-8">
        <CopyUrlField url={serverUrl} />
      </div>

      <Tabs defaultValue="chatgpt">
        <TabsList className="mb-5 w-full justify-start overflow-x-auto">
          {CLIENTS.map((c) => (
            <TabsTrigger key={c.id} value={c.id}>
              {c.label}
            </TabsTrigger>
          ))}
        </TabsList>

        {CLIENTS.map((c) => (
          <TabsContent key={c.id} value={c.id} className="rounded-xl border border-border/60 bg-card p-5 sm:p-6">
            <ClientSetup client={c.id} url={serverUrl} />
          </TabsContent>
        ))}
      </Tabs>

      <div className="mt-6 space-y-3">
        <div className="flex gap-3 rounded-xl bg-muted/60 p-4">
          <ShieldCheck className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
          <p className="text-sm text-muted-foreground leading-relaxed">
            Each client opens a sign-in screen on the last step. Sign in with your own Chapterly
            account and approve, and the assistant acts as you — it can only do what you can do.
          </p>
        </div>
        <div className="flex gap-3 rounded-xl bg-muted/60 p-4">
          <RefreshCw className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
          <p className="text-sm text-muted-foreground leading-relaxed">
            Assistants cache the list of things they can do. After we ship new features, remove and
            re-add the connector so the assistant sees them.
          </p>
        </div>
      </div>
    </div>
  );
}
```

---

## `src/pages/CoverStudio.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router-dom';
import html2canvas from 'html2canvas';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Loader2, Save, LayoutTemplate, Palette, BookOpen } from 'lucide-react';
import DrawerSelect from '@/components/DrawerSelect';
import CoverCanvas from '@/components/cover/CoverCanvas';
import CoverControls from '@/components/cover/CoverControls';
import TemplateGallery from '@/components/cover/TemplateGallery';
import { useSeo } from '@/hooks/useSeo';

const DEFAULT_CONFIG = {
  bgType: 'gradient',
  bgColor: '#1e3a8a',
  gradientFrom: '#1e3a8a',
  gradientTo: '#0ea5e9',
  imageUrl: '',
  aiPrompt: '',
  title: 'Your Story Title',
  author: 'Author Name',
  titleColor: '#ffffff',
  titleSize: 34,
  titleFont: 'Georgia, serif',
  titleAlign: 'center',
  titlePosition: 'center',
  authorColor: '#e2e8f0',
  authorSize: 16,
};

const CATEGORIES = ['Fantasy', 'Romance', 'Mystery', 'Sci-Fi', 'Thriller', 'Horror', 'Young Adult', 'Literary', 'Historical', 'Adventure', 'Drama', 'Other'];
const CATEGORY_OPTIONS = CATEGORIES.map((c) => ({ value: c, label: c }));

async function captureCover(ref) {
  const canvas = await html2canvas(ref.current, { scale: 2, backgroundColor: null, useCORS: true });
  return await new Promise((res) => canvas.toBlob(res, 'image/png'));
}

export default function CoverStudio() {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [params] = useSearchParams();
  const [config, setConfig] = useState(DEFAULT_CONFIG);
  const [templates, setTemplates] = useState([]);
  const [stories, setStories] = useState([]);
  const [selectedStory, setSelectedStory] = useState('');
  const [generating, setGenerating] = useState(false);
  const [saving, setSaving] = useState(false);
  const [buyingId, setBuyingId] = useState(null);
  const [tplTitle, setTplTitle] = useState('');
  const [tplCategory, setTplCategory] = useState('Other');
  const [tplPrice, setTplPrice] = useState(0);
  const [savingTpl, setSavingTpl] = useState(false);
  const canvasRef = useRef(null);

  useSeo({ title: 'Cover Studio — Chapterly', description: 'Design and generate covers for your stories, save them as reusable templates, and earn when others use them.' });

  const loadTemplates = async () => {
    try {
      const list = await base44.entities.CoverTemplate.list('-created_date', 60);
      setTemplates(list || []);
    } catch { setTemplates([]); }
  };

  useEffect(() => {
    loadTemplates();
  }, []);

  useEffect(() => {
    if (!user) return;
    (async () => {
      try {
        const own = await base44.entities.Story.filter({ created_by_id: user.id });
        setStories(own || []);
      } catch { setStories([]); }
    })();
  }, [user]);

  const applyTemplate = (t) => {
    const base = { ...DEFAULT_CONFIG, ...(t.config || {}) };
    if (t.cover_url) { base.bgType = 'image'; base.imageUrl = t.cover_url; }
    setConfig(base);
    toast({ title: 'Template loaded', description: t.title });
  };

  useEffect(() => {
    const tid = params.get('template');
    if (tid && templates.length) {
      const t = templates.find((x) => x.id === tid);
      if (t) applyTemplate(t);
    }
  }, [params, templates]);

  const generateArt = async () => {
    if (!config.aiPrompt?.trim()) { toast({ title: 'Describe the art first', variant: 'destructive' }); return; }
    setGenerating(true);
    try {
      const res = await base44.functions.invoke('generateCoverArt', { prompt: config.aiPrompt, style: 'dramatic, painterly, atmospheric, no text' });
      if (res.data?.url) setConfig((c) => ({ ...c, imageUrl: res.data.url }));
      else toast({ title: 'Could not generate art', description: res.data?.error, variant: 'destructive' });
    } catch (e) {
      toast({ title: 'Generation failed', description: e.message, variant: 'destructive' });
    } finally {
      setGenerating(false);
    }
  };

  const onUpload = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      setConfig((c) => ({ ...c, imageUrl: file_url }));
    } catch (err) {
      toast({ title: 'Upload failed', description: err.message, variant: 'destructive' });
    }
  };

  const saveToStory = async () => {
    if (!selectedStory) { toast({ title: 'Pick a story first', variant: 'destructive' }); return; }
    setSaving(true);
    try {
      const blob = await captureCover(canvasRef);
      const file = new File([blob], 'cover.png', { type: 'image/png' });
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      await base44.entities.Story.update(selectedStory, { cover_url: file_url });
      toast({ title: 'Cover saved', description: 'Your story cover has been updated.' });
    } catch (e) {
      toast({ title: 'Could not save', description: e.message, variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  const saveAsTemplate = async () => {
    if (!tplTitle.trim()) { toast({ title: 'Name your template', variant: 'destructive' }); return; }
    setSavingTpl(true);
    try {
      const blob = await captureCover(canvasRef);
      const file = new File([blob], 'template.png', { type: 'image/png' });
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      await base44.entities.CoverTemplate.create({
        title: tplTitle,
        cover_url: file_url,
        category: tplCategory,
        price: Number(tplPrice) || 0,
        is_free: !Number(tplPrice) || Number(tplPrice) <= 0,
        config,
      });
      toast({ title: 'Template published', description: 'It’s now in the gallery for others to use.' });
      setTplTitle(''); setTplPrice(0);
      loadTemplates();
    } catch (e) {
      toast({ title: 'Could not publish template', description: e.message, variant: 'destructive' });
    } finally {
      setSavingTpl(false);
    }
  };

  const buyTemplate = async (t) => {
    if (window.self !== window.top) { toast({ title: 'Checkout unavailable in preview', description: 'Open the published app to buy.', variant: 'destructive' }); return; }
    setBuyingId(t.id);
    try {
      const res = await base44.functions.invoke('createCheckout', { type: 'template', templateId: t.id });
      if (res.data?.url) window.location.href = res.data.url;
      else toast({ title: 'Could not start checkout', description: res.data?.error, variant: 'destructive' });
    } catch (e) {
      toast({ title: 'Checkout failed', description: e.message, variant: 'destructive' });
    } finally {
      setBuyingId(null);
    }
  };

  return (
    <div className="space-y-8">
      <div className="flex items-center gap-2">
        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
          <Palette className="w-5 h-5 text-primary" />
        </div>
        <div>
          <h1 className="font-heading text-2xl font-semibold">Cover Studio</h1>
          <p className="text-sm text-muted-foreground">Design covers, generate art, and publish templates others can use.</p>
        </div>
      </div>

      <div className="grid lg:grid-cols-2 gap-8">
        <div className="space-y-4">
          <div className="flex justify-center">
            <CoverCanvas ref={canvasRef} config={config} />
          </div>

          <div className="rounded-xl border border-border/60 bg-card p-4 space-y-3">
            <div className="flex items-center gap-2 text-sm font-medium"><BookOpen className="w-4 h-4" /> Save to a story</div>
            <div className="flex gap-2">
              <div className="flex-1">
                <DrawerSelect
                  label="Story"
                  value={selectedStory}
                  options={[
                    { value: '', label: 'Choose a story…' },
                    ...stories.map((s) => ({ value: s.id, label: s.title })),
                  ]}
                  onChange={setSelectedStory}
                />
              </div>
              <Button onClick={saveToStory} disabled={saving} className="rounded-full">
                {saving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />} Save
              </Button>
            </div>
          </div>

          <div className="rounded-xl border border-border/60 bg-card p-4 space-y-3">
            <div className="flex items-center gap-2 text-sm font-medium"><LayoutTemplate className="w-4 h-4" /> Publish as a template</div>
            <div className="grid grid-cols-2 gap-2">
              <Input placeholder="Template name" value={tplTitle} onChange={(e) => setTplTitle(e.target.value)} />
              <DrawerSelect
                label="Category"
                value={tplCategory}
                options={CATEGORY_OPTIONS}
                onChange={setTplCategory}
              />
            </div>
            <div className="flex gap-2 items-end">
              <div className="flex-1 space-y-1">
                <Label className="text-xs">Price (USD, 0 = free)</Label>
                <Input type="number" min={0} step={0.5} value={tplPrice} onChange={(e) => setTplPrice(e.target.value)} />
              </div>
              <Button onClick={saveAsTemplate} disabled={savingTpl} className="rounded-full">
                {savingTpl ? <Loader2 className="w-4 h-4 animate-spin" /> : <LayoutTemplate className="w-4 h-4" />} Publish
              </Button>
            </div>
            <p className="text-xs text-muted-foreground">Paid templates earn you money each time a reader buys them.</p>
          </div>
        </div>

        <div className="rounded-xl border border-border/60 bg-card p-4">
          <CoverControls config={config} setConfig={setConfig} onGenerate={generateArt} onUpload={onUpload} generating={generating} />
        </div>
      </div>

      <div className="space-y-3">
        <h2 className="font-heading text-lg font-semibold">Template gallery</h2>
        <TemplateGallery templates={templates} onApply={applyTemplate} onBuy={buyTemplate} buyingId={buyingId} />
      </div>
    </div>
  );
}
```

---

## `src/pages/Discover.jsx`

```javascript
import { useEffect, useState, useMemo } from 'react';
import { base44 } from '@/api/base44Client';
import StoryCard from '@/components/StoryCard';
import PullToRefresh from '@/components/PullToRefresh';
import { Search, Hash, ArrowRight, Plus, Filter } from 'lucide-react';
import { Input } from '@/components/ui/input';
import GenreDialog from '@/components/genre/GenreDialog';
import { loadGenres, subGenreNames, topLevelNames } from '@/lib/genres';

export default function Discover() {
  const [stories, setStories] = useState([]);
  const [likes, setLikes] = useState({});
  const [tag, setTag] = useState(null);
  const [q, setQ] = useState('');
  const [genres, setGenres] = useState([]);
  const [genreDialog, setGenreDialog] = useState(false);
  const [genre, setGenre] = useState('All');
  const [sub, setSub] = useState(null);

  const loadData = () =>
    Promise.all([
      base44.entities.Story.filter({ status: 'published' }, '-created_date', 80),
      base44.entities.Like.filter({ target_type: 'story' }),
      loadGenres().catch(() => []),
    ]).then(([s, all, gs]) => {
      setStories(s);
      setGenres(gs);
      const map = {};
      all.forEach((l) => { map[l.target_id] = (map[l.target_id] || 0) + 1; });
      setLikes(map);
    });

  useEffect(() => {
    loadData().catch(() => {});
  }, []);

  const tags = useMemo(() => {
    const counts = {};
    stories.forEach((s) => (s.tags || []).forEach((t) => { counts[t] = (counts[t] || 0) + 1; }));
    return Object.entries(counts).sort((a, b) => b[1] - a[1]).slice(0, 16).map(([t]) => t);
  }, [stories]);

  const genreNames = useMemo(() => {
    const known = topLevelNames(genres);
    const fromStories = stories.map((s) => s.genre).filter(Boolean);
    return [...new Set([...known, ...fromStories])];
  }, [genres, stories]);

  const subNames = useMemo(() => {
    if (genre === 'All') return [];
    const known = subGenreNames(genres, genre);
    const fromStories = stories.filter((s) => s.genre === genre).map((s) => s.sub_genre).filter(Boolean);
    return [...new Set([...known, ...fromStories])];
  }, [genres, stories, genre]);

  const query = q.toLowerCase().trim();

  const matches = useMemo(() => {
    return stories.filter((s) => {
      const matchGenre = genre === 'All' || s.genre === genre;
      const matchSub = !sub || s.sub_genre === sub;
      const matchTag = !tag || (s.tags || []).includes(tag);
      const matchQuery =
        !query ||
        s.title.toLowerCase().includes(query) ||
        (s.description || '').toLowerCase().includes(query) ||
        (s.tags || []).some((t) => t.toLowerCase().includes(query));
      return matchGenre && matchSub && matchTag && matchQuery;
    });
  }, [stories, genre, sub, tag, query]);

  const grouped = useMemo(() => {
    const order = [
      ...new Set([...topLevelNames(genres), ...matches.map((s) => s.genre).filter(Boolean)]),
    ];
    const map = {};
    matches.forEach((s) => {
      const g = s.genre || 'Other';
      (map[g] ||= []).push(s);
    });
    return order.filter((g) => map[g] && map[g].length > 0).map((g) => ({ genre: g, items: map[g] }));
  }, [matches, genres]);

  const scrollTo = (g) => {
    const el = document.getElementById(`genre-${g}`);
    if (el) el.scrollIntoView({ behavior: 'smooth', block: 'start' });
  };

  return (
    <PullToRefresh onRefresh={loadData}>
    <div className="space-y-10">
      <div>
        <h1 className="font-heading text-3xl font-semibold tracking-tight">Discover stories</h1>
        <p className="text-sm text-muted-foreground mt-1.5 max-w-lg">
          Explore new fiction series by genre and theme. Find your next obsession.
        </p>
        <div className="mt-4 relative max-w-md">
          <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
          <Input
            value={q}
            onChange={(e) => setQ(e.target.value)}
            placeholder="Search titles, descriptions, or tags"
            className="pl-9 rounded-full"
          />
        </div>
        <button
          onClick={() => setGenreDialog(true)}
          className="mt-3 inline-flex items-center gap-1.5 text-xs px-3 py-1.5 rounded-full border border-dashed border-border text-muted-foreground hover:text-foreground hover:bg-muted transition"
        >
          <Plus className="w-3.5 h-3.5" /> New genre or sub-category
        </button>
      </div>

      <div>
        <div className="flex items-center justify-between mb-3">
          <div className="flex items-center gap-2 text-sm font-medium text-muted-foreground">
            <Filter className="w-4 h-4" /> Filter by genre
          </div>
          {(genre !== 'All' || sub) && (
            <button
              onClick={() => { setGenre('All'); setSub(null); }}
              className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-2"
            >
              Clear
            </button>
          )}
        </div>
        <div className="flex flex-wrap gap-2">
          <button
            onClick={() => { setGenre('All'); setSub(null); }}
            className={`text-sm px-3 py-1.5 rounded-full transition ${
              genre === 'All' ? 'bg-foreground text-background' : 'border border-border text-muted-foreground hover:text-foreground hover:bg-muted'
            }`}
          >
            All genres
          </button>
          {genreNames.map((g) => (
            <button
              key={g}
              onClick={() => { setGenre(g); setSub(null); }}
              className={`text-sm px-3 py-1.5 rounded-full transition ${
                genre === g ? 'bg-foreground text-background' : 'border border-border text-muted-foreground hover:text-foreground hover:bg-muted'
              }`}
            >
              {g}
            </button>
          ))}
        </div>

        {subNames.length > 0 && (
          <div className="flex flex-wrap items-center gap-2 mt-3">
            <span className="text-xs text-muted-foreground">Sub-categories:</span>
            <button
              onClick={() => setSub(null)}
              className={`text-xs px-2.5 py-1 rounded-full transition ${
                !sub ? 'bg-muted text-foreground' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
              }`}
            >
              All
            </button>
            {subNames.map((s) => (
              <button
                key={s}
                onClick={() => setSub(sub === s ? null : s)}
                className={`text-xs px-2.5 py-1 rounded-full transition ${
                  sub === s ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground hover:bg-muted'
                }`}
              >
                {s}
              </button>
            ))}
          </div>
        )}
      </div>

      {tags.length > 0 && (
        <div>
          <div className="flex items-center gap-2 mb-3 text-sm font-medium text-muted-foreground">
            <Hash className="w-4 h-4" /> Browse by tag
          </div>
          <div className="flex flex-wrap gap-2">
            <button
              onClick={() => setTag(null)}
              className={`text-sm px-3 py-1.5 rounded-full transition ${
                !tag ? 'bg-foreground text-background' : 'border border-border text-muted-foreground hover:text-foreground hover:bg-muted'
              }`}
            >
              All
            </button>
            {tags.map((t) => (
              <button
                key={t}
                onClick={() => setTag(tag === t ? null : t)}
                className={`text-sm px-3 py-1.5 rounded-full transition ${
                  tag === t ? 'bg-foreground text-background' : 'border border-border text-muted-foreground hover:text-foreground hover:bg-muted'
                }`}
              >
                #{t}
              </button>
            ))}
          </div>
        </div>
      )}

      {grouped.length > 1 && (
        <div className="flex flex-wrap gap-2 border-y border-border/60 py-3">
          {grouped.map(({ genre, items }) => (
            <button
              key={genre}
              onClick={() => scrollTo(genre)}
              className="text-xs px-3 py-1.5 rounded-full border border-border text-muted-foreground hover:text-foreground hover:bg-muted transition"
            >
              {genre} <span className="opacity-60">({items.length})</span>
            </button>
          ))}
        </div>
      )}

      {grouped.length === 0 ? (
        <p className="text-muted-foreground text-sm">No stories found. Try a different genre, sub-category, tag, or search.</p>
      ) : (
        <div className="space-y-12">
          {grouped.map(({ genre, items }) => (
            <section key={genre} id={`genre-${genre}`} className="scroll-mt-20">
              <div className="flex items-center justify-between mb-4">
                <h2 className="font-heading text-xl font-semibold">{genre}</h2>
                <span className="text-xs text-muted-foreground">{items.length} {items.length === 1 ? 'story' : 'stories'}</span>
              </div>
              <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-5">
                {items.map((s) => (
                  <StoryCard key={s.id} story={s} likeCount={likes[s.id] || 0} />
                ))}
              </div>
            </section>
          ))}
        </div>
      )}
      <GenreDialog
        open={genreDialog}
        onOpenChange={setGenreDialog}
        onCreated={() => loadData().catch(() => {})}
      />
    </div>
    </PullToRefresh>
  );
}
```

---

## `src/pages/Earnings.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { Wallet, TrendingUp, Clock, ArrowDownToLine, CreditCard, CheckCircle2, ExternalLink, Loader2 } from 'lucide-react';

export default function Earnings() {
  const { user, refresh } = useCurrentUser();
  const { toast } = useToast();
  const [purchases, setPurchases] = useState([]);
  const [payouts, setPayouts] = useState([]);
  const [breakdown, setBreakdown] = useState([]);
  const [connect, setConnect] = useState(null);
  const [loadingConnect, setLoadingConnect] = useState(true);
  const [paying, setPaying] = useState(false);

  useEffect(() => {
    if (!user) return;
    let active = true;
    (async () => {
      try {
        const pur = await base44.entities.Purchase.filter({ writer_id: user.id }, '-created_date', 100);
        if (!active) return;
        setPurchases(pur);
        const storyMap = {};
        for (const p of pur) {
          try {
            const ch = await base44.entities.Chapter.get(p.chapter_id);
            const sid = ch.story_id;
            if (!storyMap[sid]) storyMap[sid] = { story_id: sid, title: '', earnings: 0, count: 0 };
            storyMap[sid].earnings += p.writer_share || 0;
            storyMap[sid].count += 1;
          } catch {}
        }
        for (const sid of Object.keys(storyMap)) {
          try { const s = await base44.entities.Story.get(sid); storyMap[sid].title = s.title; } catch {}
        }
        if (active) setBreakdown(Object.values(storyMap).sort((a, b) => b.earnings - a.earnings));
        const po = await base44.entities.Payout.filter({ writer_id: user.id }, '-created_date', 50);
        if (active) setPayouts(po);
        await fetchConnect();
      } catch {}
    })();
    return () => { active = false; };
  }, [user]);

  const fetchConnect = async () => {
    setLoadingConnect(true);
    try {
      const res = await base44.functions.invoke('stripeConnect', { mode: 'status' });
      if (res.data) setConnect(res.data);
    } catch {
      setConnect(null);
    } finally {
      setLoadingConnect(false);
    }
  };

  const totalEarnings = purchases.reduce((s, p) => s + (p.writer_share || 0), 0);
  const paidOut = payouts.filter((p) => p.status === 'paid').reduce((s, p) => s + p.amount, 0);
  const pendingPayouts = payouts.filter((p) => p.status === 'pending').reduce((s, p) => s + p.amount, 0);
  const balance = totalEarnings - paidOut - pendingPayouts;

  const connectStripe = async () => {
    if (window.self !== window.top) {
      toast({ title: 'Onboarding unavailable in preview', description: 'Open the published app to connect Stripe.', variant: 'destructive' });
      return;
    }
    try {
      const res = await base44.functions.invoke('stripeConnect', { mode: 'onboard' });
      if (res.data?.url) {
        window.location.href = res.data.url;
      } else {
        toast({ title: 'Could not start onboarding', description: res.data?.error, variant: 'destructive' });
      }
    } catch (e) {
      toast({ title: 'Onboarding failed', description: e.message, variant: 'destructive' });
    }
  };

  const openDashboard = async () => {
    try {
      const res = await base44.functions.invoke('stripeConnect', { mode: 'dashboard' });
      if (res.data?.url) window.open(res.data.url, '_blank');
      else toast({ title: 'Could not open dashboard', description: res.data?.error, variant: 'destructive' });
    } catch (e) {
      toast({ title: 'Failed', description: e.message, variant: 'destructive' });
    }
  };

  const requestPayout = async () => {
    if (balance <= 0) return toast({ title: 'No balance to withdraw' });
    if (!connect?.charges_enabled) return toast({ title: 'Connect Stripe first', description: 'Complete onboarding to receive payouts.', variant: 'destructive' });
    setPaying(true);
    try {
      const res = await base44.functions.invoke('requestPayout', {});
      if (res.data?.ok) {
        const po = await base44.entities.Payout.filter({ writer_id: user.id }, '-created_date', 50);
        setPayouts(po);
        toast({ title: 'Payout sent', description: `$${res.data.payout.amount.toFixed(2)} transferred to your Stripe account.` });
      } else {
        toast({ title: 'Payout failed', description: res.data?.error, variant: 'destructive' });
      }
    } catch (e) {
      toast({ title: 'Payout failed', description: e.message, variant: 'destructive' });
    } finally {
      setPaying(false);
    }
  };

  if (!user) return <p className="text-muted-foreground text-sm">Sign in to view earnings.</p>;

  const connected = connect?.connected;
  const ready = connected && connect?.charges_enabled;

  return (
    <div className="space-y-8">
      <div>
        <h1 className="font-heading text-3xl font-semibold tracking-tight">Earnings</h1>
        <p className="text-muted-foreground text-sm mt-1">Track your chapter revenue and get paid automatically via Stripe.</p>
      </div>

      <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
        <Stat icon={Wallet} label="Available balance" value={`$${balance.toFixed(2)}`} />
        <Stat icon={TrendingUp} label="Total earned" value={`$${totalEarnings.toFixed(2)}`} />
        <Stat icon={Clock} label="Pending payouts" value={`$${pendingPayouts.toFixed(2)}`} />
        <Stat icon={ArrowDownToLine} label="Paid out" value={`$${paidOut.toFixed(2)}`} />
      </div>

      <section>
        <h2 className="font-heading text-xl font-semibold mb-4">Stripe payout account</h2>
        <div className="rounded-xl border border-border/60 p-5 space-y-4 max-w-lg">
          {loadingConnect ? (
            <div className="flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="w-4 h-4 animate-spin" /> Checking connection…</div>
          ) : !connected ? (
            <>
              <div className="flex items-center gap-2 text-sm"><CreditCard className="w-4 h-4 text-muted-foreground" /> No Stripe account connected yet.</div>
              <p className="text-xs text-muted-foreground">Connect a Stripe account to receive automatic payouts. You'll onboard once, then withdraw anytime.</p>
              <Button onClick={connectStripe} className="rounded-full"><CreditCard className="w-4 h-4 mr-1.5" /> Connect with Stripe</Button>
            </>
          ) : !ready ? (
            <>
              <div className="flex items-center gap-2 text-sm"><Clock className="w-4 h-4 text-amber-500" /> Onboarding incomplete.</div>
              <p className="text-xs text-muted-foreground">Finish setting up your Stripe account to enable payouts.</p>
              <Button onClick={connectStripe} variant="outline" className="rounded-full">Resume onboarding</Button>
            </>
          ) : (
            <>
              <div className="flex items-center gap-2 text-sm"><CheckCircle2 className="w-4 h-4 text-emerald-500" /> Stripe account connected and ready for payouts.</div>
              <div className="flex gap-2">
                <Button onClick={requestPayout} disabled={balance <= 0 || paying} className="rounded-full">
                  {paying ? <Loader2 className="w-4 h-4 animate-spin" /> : <ArrowDownToLine className="w-4 h-4 mr-1.5" />}
                  {paying ? 'Processing…' : `Withdraw $${balance.toFixed(2)}`}
                </Button>
                <Button onClick={openDashboard} variant="outline" className="rounded-full">
                  <ExternalLink className="w-4 h-4 mr-1.5" /> Stripe dashboard
                </Button>
              </div>
            </>
          )}
        </div>
      </section>

      <section>
        <h2 className="font-heading text-xl font-semibold mb-4">Per-story breakdown</h2>
        {breakdown.length === 0 ? (
          <p className="text-sm text-muted-foreground">No sales yet. When readers unlock your paid chapters, earnings will appear here.</p>
        ) : (
          <div className="divide-y divide-border rounded-xl border border-border/60 overflow-hidden">
            {breakdown.map((b) => (
              <div key={b.story_id} className="flex items-center justify-between px-4 py-3">
                <div className="min-w-0">
                  <p className="font-medium text-sm truncate">{b.title || 'Untitled story'}</p>
                  <p className="text-xs text-muted-foreground">{b.count} unlock{b.count !== 1 ? 's' : ''}</p>
                </div>
                <span className="font-semibold text-sm">${b.earnings.toFixed(2)}</span>
              </div>
            ))}
          </div>
        )}
      </section>

      <section>
        <h2 className="font-heading text-xl font-semibold mb-4">Transaction history</h2>
        {purchases.length === 0 ? (
          <p className="text-sm text-muted-foreground">No transactions yet.</p>
        ) : (
          <div className="divide-y divide-border rounded-xl border border-border/60 overflow-hidden">
            {purchases.map((p) => (
              <div key={p.id} className="flex items-center justify-between px-4 py-3">
                <div>
                  <p className="text-sm font-medium">{p.payment_method === 'manual' ? 'Bank transfer' : p.payment_method === 'safepay' ? 'SafePay' : 'Card'} · ${p.amount.toFixed(2)}</p>
                  <p className="text-xs text-muted-foreground">{new Date(p.created_date).toLocaleDateString()}</p>
                </div>
                <span className="text-sm text-emerald-600 font-medium">+${(p.writer_share || 0).toFixed(2)}</span>
              </div>
            ))}
          </div>
        )}
      </section>

      <section>
        <h2 className="font-heading text-xl font-semibold mb-4">Payout history</h2>
        {payouts.length === 0 ? (
          <p className="text-sm text-muted-foreground">No payouts yet.</p>
        ) : (
          <div className="divide-y divide-border rounded-xl border border-border/60 overflow-hidden">
            {payouts.map((p) => (
              <div key={p.id} className="flex items-center justify-between px-4 py-3">
                <div>
                  <p className="text-sm font-medium">${p.amount.toFixed(2)} · {p.method || 'bank transfer'}</p>
                  <p className="text-xs text-muted-foreground">{new Date(p.created_date).toLocaleDateString()}</p>
                </div>
                <span className={`text-xs px-2 py-0.5 rounded ${p.status === 'paid' ? 'bg-emerald-500/10 text-emerald-600' : 'bg-amber-500/10 text-amber-600'}`}>{p.status}</span>
              </div>
            ))}
          </div>
        )}
      </section>
    </div>
  );
}

function Stat({ icon: Icon, label, value }) {
  return (
    <div className="rounded-xl border border-border/60 p-4">
      <div className="flex items-center gap-2 text-muted-foreground"><Icon className="w-4 h-4" /><span className="text-xs">{label}</span></div>
      <p className="font-heading text-xl font-semibold mt-1.5">{value}</p>
    </div>
  );
}
```

---

## `src/pages/ForgotPassword.jsx`

```javascript
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { base44 } from "@/api/base44Client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Mail, ArrowLeft, Loader2 } from "lucide-react";
import AuthLayout from "@/components/AuthLayout";

export default function ForgotPassword() {
  const [email, setEmail] = useState("");
  const [loading, setLoading] = useState(false);
  const [sent, setSent] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setLoading(true);
    try {
      await base44.auth.resetPasswordRequest(email);
    } catch {
      // Always show success regardless
    } finally {
      setLoading(false);
      setSent(true);
    }
  };

  return (
    <AuthLayout
      icon={Mail}
      title="Reset password"
      subtitle="We'll send you a link to reset it"
      footer={
        <Link to="/login" className="text-primary font-medium hover:underline">
          <ArrowLeft className="w-3 h-3 inline mr-1" />Back to log in
        </Link>
      }
    >
      {sent ? (
        <p className="text-sm text-foreground text-center">
          If an account exists with that email, you'll receive a password reset link shortly.
        </p>
      ) : (
        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="email">Email address</Label>
            <div className="relative">
              <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
              <Input
                id="email"
                type="email"
                autoComplete="email"
                autoFocus
                placeholder="you@example.com"
                value={email}
                onChange={(e) => setEmail(e.target.value)}
                className="pl-10 h-12"
                required
              />
            </div>
          </div>
          <Button type="submit" className="w-full h-12 font-medium" disabled={loading}>
            {loading ? (
              <>
                <Loader2 className="w-4 h-4 mr-2 animate-spin" />
                Sending...
              </>
            ) : (
              "Send reset link"
            )}
          </Button>
        </form>
      )}
    </AuthLayout>
  );
}

```

---

## `src/pages/Home.jsx`

```javascript
import { useEffect, useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import StoryCard from '@/components/StoryCard';
import PullToRefresh from '@/components/PullToRefresh';
import { Sparkles, BookOpen, Compass, Bot } from 'lucide-react';
import { useSeo } from '@/hooks/useSeo';

function countWords(html) {
  const text = (html || '').replace(/<[^>]+>/g, ' ').trim();
  return text ? text.split(/\s+/).length : 0;
}

export default function Home() {
  const { user } = useCurrentUser();
  useSeo({
    title: 'Chapterly — Read & write serialized fiction',
    description: 'Chapterly is a serialized fiction platform to discover, follow, and support independent storytellers — read chapter by chapter, unlock premium chapters, subscribe to writers, and publish your own stories.',
    url: '/',
    jsonLd: {
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      name: 'Chapterly',
      url: 'https://chapterly.ariamalik.com',
      description: 'Discover, follow, and support independent storytellers with a seamless, serialized reading experience.',
      potentialAction: {
        '@type': 'SearchAction',
        target: 'https://chapterly.ariamalik.com/browse?q={query}',
        'query-input': 'required name=query',
      },
    },
  });
  const [trending, setTrending] = useState([]);
  const [followedChapters, setFollowedChapters] = useState([]);
  const [followedStories, setFollowedStories] = useState({});
  const [likeCounts, setLikeCounts] = useState({});

  const loadTrending = () =>
    Promise.all([
      base44.entities.Story.filter({ status: 'published' }, '-created_date', 40),
      base44.entities.Like.filter({ target_type: 'story' }),
    ]).then(([s, all]) => {
      setTrending(s);
      const map = {};
      all.forEach((l) => { map[l.target_id] = (map[l.target_id] || 0) + 1; });
      setLikeCounts(map);
    });

  useEffect(() => {
    loadTrending().catch(() => {});
  }, []);

  const rankedTrending = useMemo(() => {
    const now = Date.now();
    const scored = trending.map((s) => {
      const ageDays = Math.min(120, (now - new Date(s.created_date).getTime()) / 86400000);
      const recency = Math.max(0, 30 - ageDays) / 30; // 0..1, fades over a month
      const score = (likeCounts[s.id] || 0) * 3 + (s.views || 0) * 0.5 + recency * 10;
      return { ...s, _score: score };
    });
    return scored.sort((a, b) => b._score - a._score).slice(0, 18);
  }, [trending, likeCounts]);

  useEffect(() => {
    if (!user) return;
    let active = true;
    (async () => {
      try {
        const follows = await base44.entities.Follow.filter({ follower_id: user.id });
        const writerIds = follows.map((f) => f.writer_id);
        if (!writerIds.length || !active) return;
        const storiesByWriter = {};
        for (const wid of writerIds) {
          const s = await base44.entities.Story.filter({ created_by_id: wid, status: 'published' });
          s.forEach((x) => (storiesByWriter[x.id] = x));
        }
        const storyIds = Object.keys(storiesByWriter);
        if (!storyIds.length) return;
        const chapters = await base44.entities.Chapter.filter({ published: true }, '-created_date', 20);
        const mine = chapters.filter((c) => storyIds.includes(c.story_id)).slice(0, 8);
        if (active) {
          setFollowedChapters(mine);
          setFollowedStories(storiesByWriter);
        }
      } catch {}
    })();
    return () => { active = false; };
  }, [user]);

  return (
    <PullToRefresh onRefresh={loadTrending}>
    <div className="space-y-14">
      <section className="text-center py-8">
        <h1 className="font-heading text-4xl sm:text-5xl font-semibold tracking-tight">
          Stories worth your next chapter.
        </h1>
        <p className="text-muted-foreground mt-3 max-w-xl mx-auto">
          Discover serialized fiction from emerging writers. Read the first chapters free, then unlock the rest or subscribe to your favorites.
        </p>
        <div className="mt-6 flex gap-2 justify-center">
          <Link
            to="/browse"
            className="inline-flex items-center gap-1.5 rounded-full bg-foreground text-background px-5 py-2.5 text-sm font-medium hover:opacity-90 transition"
          >
            <BookOpen className="w-4 h-4" /> Browse stories
          </Link>
          <Link
            to="/dashboard"
            className="inline-flex items-center gap-1.5 rounded-full border px-5 py-2.5 text-sm font-medium hover:bg-muted transition"
          >
            <Sparkles className="w-4 h-4" /> Start writing
          </Link>
          <Link
            to="/recommendations"
            className="inline-flex items-center gap-1.5 rounded-full border px-5 py-2.5 text-sm font-medium hover:bg-muted transition"
          >
            <Compass className="w-4 h-4" /> For you
          </Link>
          <Link
            to="/assistant"
            className="inline-flex items-center gap-1.5 rounded-full border px-5 py-2.5 text-sm font-medium hover:bg-muted transition"
          >
            <Bot className="w-4 h-4" /> Ask Chapterly
          </Link>
        </div>
      </section>

      {followedChapters.length > 0 && (
        <section>
          <h2 className="font-heading text-2xl font-semibold mb-5">New from writers you follow</h2>
          <div className="grid sm:grid-cols-2 lg:grid-cols-4 gap-4">
            {followedChapters.map((c) => {
              const s = followedStories[c.story_id];
              return (
                <Link
                  key={c.id}
                  to={`/read/${c.id}`}
                  className="block rounded-xl border border-border/60 bg-card p-4 hover:shadow-sm transition"
                >
                  <p className="text-[11px] uppercase tracking-wide text-muted-foreground">{s?.title}</p>
                  <h3 className="font-heading font-semibold text-sm mt-1 line-clamp-2">{c.title}</h3>
                  <p className="text-xs text-muted-foreground mt-1">{c.word_count || countWords(c.body)} words</p>
                </Link>
              );
            })}
          </div>
        </section>
      )}

      <section>
        <h2 className="font-heading text-2xl font-semibold mb-5">Trending now</h2>
        {trending.length === 0 ? (
          <p className="text-muted-foreground text-sm">
            No stories yet — be the first to publish one from your <Link to="/dashboard" className="underline">writer dashboard</Link>.
          </p>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-5">
            {rankedTrending.map((s) => (
              <StoryCard key={s.id} story={s} likeCount={likeCounts[s.id] || 0} />
            ))}
          </div>
        )}
      </section>
    </div>
    </PullToRefresh>
  );
}
```

---

## `src/pages/InstagramPublish.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Image } from '@/components/ui/image';
import { Instagram, Loader2, CheckCircle2 } from 'lucide-react';

const CONNECTOR_ID = '6a915ab0a8d4e91b72704571';

export default function InstagramPublish() {
  const { toast } = useToast();
  const [authed, setAuthed] = useState(false);
  const [user, setUser] = useState(null);
  const [stories, setStories] = useState([]);
  const [connected, setConnected] = useState(null);
  const [posting, setPosting] = useState(null);
  const [connecting, setConnecting] = useState(false);

  const detectAndLoad = async (u) => {
    const s = await base44.entities.Story.filter({ created_by_id: u.id }, '-created_date');
    setStories(s);
    const withCover = s.find((x) => x.cover_url);
    if (withCover) {
      try {
        await base44.functions.invoke('postMyStoryToInstagram', { story_id: withCover.id, dry_run: true });
        setConnected(true);
      } catch {
        setConnected(false);
      }
    } else {
      setConnected(false);
    }
  };

  useEffect(() => {
    base44.auth.isAuthenticated().then(async (ok) => {
      setAuthed(ok);
      if (ok) {
        const me = await base44.auth.me();
        setUser(me);
        await detectAndLoad(me);
      }
    });
  }, []);

  const handleConnect = async () => {
    setConnecting(true);
    try {
      const url = await base44.connectors.connectAppUser(CONNECTOR_ID);
      const popup = window.open(url, '_blank');
      const timer = setInterval(() => {
        if (!popup || popup.closed) {
          clearInterval(timer);
          detectAndLoad(user);
        }
      }, 600);
    } catch {
      toast({ title: 'Could not start Instagram connection', variant: 'destructive' });
    } finally {
      setConnecting(false);
    }
  };

  const handlePost = async (story) => {
    setPosting(story.id);
    try {
      await base44.functions.invoke('postMyStoryToInstagram', { story_id: story.id });
      toast({ title: `Posted "${story.title}" to Instagram` });
      setConnected(true);
    } catch (e) {
      toast({ title: e?.response?.data?.error || 'Post failed', variant: 'destructive' });
    } finally {
      setPosting(null);
    }
  };

  if (!authed) {
    return (
      <div className="max-w-md mx-auto mt-20 text-center space-y-4">
        <Instagram className="w-10 h-10 mx-auto text-primary" />
        <p className="text-muted-foreground">Sign in to publish your stories to Instagram.</p>
        <Button onClick={() => base44.auth.redirectToLogin()}>Sign in</Button>
      </div>
    );
  }

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <div>
        <h1 className="font-heading text-3xl font-semibold tracking-tight flex items-center gap-2">
          <Instagram className="w-7 h-7 text-primary" /> Instagram publishing
        </h1>
        <p className="text-muted-foreground text-sm mt-1">Post your top-rated stories straight to your Instagram Business feed.</p>
      </div>

      <div className="rounded-xl border border-border/60 p-4 flex items-center justify-between gap-4">
        <div className="flex items-center gap-3">
          {connected ? <CheckCircle2 className="w-5 h-5 text-emerald-500" /> : <Instagram className="w-5 h-5 text-muted-foreground" />}
          <div>
            <p className="font-medium text-sm">{connected ? 'Instagram connected' : 'Connect your Instagram Business account'}</p>
            <p className="text-xs text-muted-foreground">{connected ? 'You can publish stories below.' : 'Required before posting.'}</p>
          </div>
        </div>
        {!connected && (
          <Button onClick={handleConnect} disabled={connecting}>
            {connecting ? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> : <Instagram className="w-4 h-4 mr-1.5" />} Connect
          </Button>
        )}
      </div>

      <div className="space-y-3">
        {stories.length === 0 ? (
          <p className="text-sm text-muted-foreground">You have no stories yet.</p>
        ) : (
          stories.map((s) => (
            <div key={s.id} className="flex items-center gap-4 p-3 rounded-xl border border-border/60">
              <div className="w-12 h-16 rounded-md overflow-hidden bg-muted shrink-0">
                {s.cover_url ? <Image src={s.cover_url} fittingType="fill" className="w-full h-full" /> : null}
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="font-heading font-semibold truncate">{s.title}</h3>
                <p className="text-xs text-muted-foreground">{s.genre} · {s.status}</p>
              </div>
              <Button size="sm" onClick={() => handlePost(s)} disabled={!s.cover_url || posting === s.id || !connected}>
                {posting === s.id ? <Loader2 className="w-4 h-4 mr-1.5 animate-spin" /> : <Instagram className="w-4 h-4 mr-1.5" />}
                {s.cover_url ? 'Post' : 'No cover'}
              </Button>
            </div>
          ))
        )}
      </div>
    </div>
  );
}
```

---

## `src/pages/Login.jsx`

```javascript
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { base44 } from "@/api/base44Client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { LogIn, Mail, Lock, Loader2 } from "lucide-react";
import AuthLayout from "@/components/AuthLayout";
import GoogleIcon from "@/components/GoogleIcon";
import AppleIcon from "@/components/AppleIcon";
import { safeReturnTo } from "@/lib/authReturnTo";

export default function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  // Post-login destination (e.g. the MCP OAuth consent page sends users here
  // with returnTo so the grant flow can resume). Same-origin paths only.
  const returnTo = safeReturnTo();

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      await base44.auth.loginViaEmailPassword(email, password);
      window.location.href = returnTo;
    } catch (err) {
      setError(err.message || "Invalid email or password");
    } finally {
      setLoading(false);
    }
  };

  const handleGoogle = () => {
    base44.auth.loginWithProvider("google", returnTo);
  };

  const handleApple = () => {
    base44.auth.loginWithProvider("apple", returnTo);
  };

  return (
    <AuthLayout
      icon={LogIn}
      title="Welcome back"
      subtitle="Log in to your account"
      footer={
        <>
          Don't have an account?{" "}
          <Link
            to={"/register" + (returnTo !== "/" ? "?returnTo=" + encodeURIComponent(returnTo) : "")}
            className="text-primary font-medium hover:underline"
          >
            Create one
          </Link>
        </>
      }
    >
      <div className="space-y-2.5 mb-6">
        <Button
          variant="outline"
          className="w-full h-12 text-sm font-medium bg-black text-white border-black hover:bg-black/90 hover:text-white"
          onClick={handleApple}
        >
          <AppleIcon className="w-5 h-5 mr-2" />
          Continue with Apple
        </Button>
        <Button
          variant="outline"
          className="w-full h-12 text-sm font-medium"
          onClick={handleGoogle}
        >
          <GoogleIcon className="w-5 h-5 mr-2" />
          Continue with Google
        </Button>
      </div>

      <div className="relative mb-6">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-border" />
        </div>
        <div className="relative flex justify-center text-xs uppercase">
          <span className="bg-card px-3 text-muted-foreground">or</span>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="email">Email</Label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
            <Input
              id="email"
              type="email"
              autoComplete="email"
              autoFocus
              placeholder="you@example.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="pl-10 h-12"
              required
            />
          </div>
        </div>
        <div className="space-y-2">
          <div className="flex items-center justify-between">
            <Label htmlFor="password">Password</Label>
            <Link to="/forgot-password" className="text-xs text-primary hover:underline">
              Forgot password?
            </Link>
          </div>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
            <Input
              id="password"
              type="password"
              autoComplete="current-password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="pl-10 h-12"
              required
            />
          </div>
        </div>
        <Button type="submit" className="w-full h-12 font-medium" disabled={loading}>
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Logging in...
            </>
          ) : (
            "Log in"
          )}
        </Button>
      </form>
    </AuthLayout>
  );
}
```

---

## `src/pages/MarketingDashboard.jsx`

```javascript
import { useEffect, useState } from 'react';
import { base44 } from '@/api/base44Client';
import { BookOpen, UserPlus, CreditCard, RefreshCw } from 'lucide-react';
import KpiCard from '@/components/marketing/KpiCard';
import KpiTrendChart from '@/components/marketing/KpiTrendChart';
import CombinedTrendChart from '@/components/marketing/CombinedTrendChart';
import { Button } from '@/components/ui/button';
import { useSeo } from '@/hooks/useSeo';
import { useCurrentUser } from '@/hooks/useCurrentUser';

const ICONS = [BookOpen, UserPlus, CreditCard];
const COLORS = ['hsl(var(--chart-1))', 'hsl(var(--chart-2))', 'hsl(var(--chart-3))'];

export default function MarketingDashboard() {
  useSeo({ title: 'Marketing KPIs — Chapterly' });
  const { user } = useCurrentUser();
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await base44.functions.invoke('getMarketingKpis', {});
      setData(res.data);
    } catch (e) {
      setError(e.response?.data?.error || e.message);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { if (user?.role === 'admin') load(); }, [user]);

  if (!user) return <p className="text-muted-foreground text-sm">Loading…</p>;
  if (user.role !== 'admin') return <p className="text-muted-foreground text-sm">You don't have access to this page.</p>;

  return (
    <div className="space-y-6">
      <div className="flex items-center justify-between">
        <div>
          <h1 className="font-heading text-2xl font-semibold tracking-tight">Marketing KPIs</h1>
          <p className="text-sm text-muted-foreground">Weekly growth trends across reads, signups, and paid conversions.</p>
        </div>
        <Button variant="outline" size="sm" onClick={load} disabled={loading}>
          <RefreshCw className={`w-4 h-4 mr-1.5 ${loading ? 'animate-spin' : ''}`} /> Refresh
        </Button>
      </div>

      {error && (
        <div className="rounded-xl border border-destructive/30 bg-destructive/5 p-4 text-sm text-destructive">{error}</div>
      )}

      {loading && !data ? (
        <div className="grid gap-4 sm:grid-cols-3">
          {[0, 1, 2].map((i) => <div key={i} className="h-32 rounded-2xl bg-muted animate-pulse" />)}
        </div>
      ) : data ? (
        <>
          <div className="grid gap-4 sm:grid-cols-3">
            {data.kpis.map((k, i) => <KpiCard key={k.label} {...k} icon={ICONS[i]} />)}
          </div>
          <CombinedTrendChart kpis={data.kpis} />
          <div className="grid gap-4 lg:grid-cols-3">
            {data.kpis.map((k, i) => <KpiTrendChart key={k.label} {...k} color={COLORS[i]} />)}
          </div>
        </>
      ) : null}
    </div>
  );
}
```

---

## `src/pages/Membership.jsx`

```javascript
import { useEffect, useState } from 'react';
import { useSearchParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { Crown, Sparkles, Check, Loader2 } from 'lucide-react';

const PRICE = 9.99;

export default function Membership() {
  const { toast } = useToast();
  const [params] = useSearchParams();
  const [membership, setMembership] = useState(null);
  const [loading, setLoading] = useState(true);
  const [starting, setStarting] = useState(false);

  const fetchMembership = async () => {
    try {
      const me = await base44.auth.me();
      if (!me) { setLoading(false); return; }
      const subs = await base44.entities.Subscription.filter({
        reader_id: me.id,
        type: 'membership',
        status: 'active',
      });
      setMembership(subs[0] || null);
    } catch {
      setMembership(null);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchMembership();
    if (params.get('status') === 'success') {
      toast({ title: 'Welcome to Chapterly Membership!', description: 'Your subscription is now active.' });
    } else if (params.get('status') === 'canceled') {
      toast({ title: 'Checkout canceled', variant: 'destructive' });
    }
  }, []);

  const handleSubscribe = async () => {
    if (window.self !== window.top) {
      toast({ title: 'Checkout unavailable in preview', description: 'Open the published app to subscribe.', variant: 'destructive' });
      return;
    }
    setStarting(true);
    try {
      const res = await base44.functions.invoke('createCheckout', { type: 'membership' });
      if (res.data?.url) window.location.href = res.data.url;
    } catch (e) {
      toast({ title: 'Could not start checkout', description: e.message, variant: 'destructive' });
    } finally {
      setStarting(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center py-24">
        <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
      </div>
    );
  }

  if (membership) {
    const renews = membership.renews_at ? new Date(membership.renews_at).toLocaleDateString() : null;
    return (
      <div className="max-w-2xl mx-auto">
        <div className="rounded-2xl border border-border bg-gradient-to-b from-amber-50 to-background p-8 text-center">
          <div className="mx-auto w-14 h-14 rounded-full bg-amber-500 text-white flex items-center justify-center mb-4">
            <Crown className="w-6 h-6" />
          </div>
          <h1 className="font-heading text-2xl font-semibold">You're a Chapterly Member</h1>
          <p className="text-sm text-muted-foreground mt-2">
            Enjoy unlimited access to every premium chapter across the platform.
          </p>
          {renews && (
            <p className="text-sm text-muted-foreground mt-4">
              Next renewal: <span className="font-medium text-foreground">{renews}</span>
            </p>
          )}
          <p className="text-xs text-muted-foreground mt-6">
            Manage or cancel your membership anytime via Stripe's customer portal.
          </p>
          <Button asChild variant="outline" size="sm" className="rounded-full mt-5">
            <Link to="/subscription-assistant">Ask the Subscription Assistant</Link>
          </Button>
        </div>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto">
      <div className="text-center mb-8">
        <div className="mx-auto w-14 h-14 rounded-full bg-foreground text-background flex items-center justify-center mb-4">
          <Crown className="w-6 h-6" />
        </div>
        <h1 className="font-heading text-3xl font-semibold">Chapterly Membership</h1>
        <p className="text-muted-foreground mt-2">One subscription. Every story. Zero paywalls.</p>
      </div>

      <div className="rounded-2xl border border-border p-8 bg-card">
        <div className="flex items-baseline justify-center gap-1">
          <span className="font-heading text-4xl font-semibold">${PRICE}</span>
          <span className="text-muted-foreground">/month</span>
        </div>
        <ul className="mt-6 space-y-3 text-sm">
          {[
            'Unlimited access to all premium chapters',
            'Read across every author and genre',
            'Support storytellers directly',
            'Cancel anytime',
          ].map((f) => (
            <li key={f} className="flex items-center gap-2">
              <Check className="w-4 h-4 text-emerald-500 shrink-0" />
              <span>{f}</span>
            </li>
          ))}
        </ul>
        <Button onClick={handleSubscribe} disabled={starting} className="w-full mt-6 rounded-full" size="lg">
          {starting ? <Loader2 className="w-4 h-4 animate-spin" /> : <Sparkles className="w-4 h-4 mr-1.5" />}
          {starting ? 'Redirecting…' : 'Subscribe with Stripe'}
        </Button>
        <p className="text-[11px] text-muted-foreground text-center mt-4">
          Secure recurring payment powered by Stripe. You can cancel at any time.
        </p>
      </div>
    </div>
  );
}
```

---

## `src/pages/Mfa.jsx`

```javascript
import React, { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Loader2, Lock, Mail } from "lucide-react";
import GoogleIcon from "@/components/GoogleIcon";
import MfaFlow from "@/components/MfaFlow";
import MfaManage from "@/components/MfaManage";
import { MfaHeader, MfaNotice, MfaScreen, useAppInfo } from "@/components/MfaParts";
import { finishSignIn, resumeMfa, signInToManageMfa, signInWithProvider } from "@/lib/authMfaFlow";
import { safeReturnTo } from "@/lib/authReturnTo";

const PROVIDERS = [
  { id: "google", flag: "enable_google_login", name: "Google" },
  { id: "microsoft", flag: "enable_microsoft_login", name: "Microsoft" },
  { id: "facebook", flag: "enable_facebook_login", name: "Facebook" },
  { id: "apple", flag: "enable_apple_login", name: "Apple" },
];

// /mfa: finishes a Google, Microsoft, Facebook, Apple or SSO sign-in that needs a second step
// (?mfa_code=…), and opened directly it is the two-factor authentication settings page.
export default function Mfa() {
  const returnTo = safeReturnTo();
  const [challenge, setChallenge] = useState(null);
  const [managing, setManaging] = useState(null);
  const [resuming, setResuming] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    resumeMfa()
      .then((result) => {
        // A remembered device signs in straight away; otherwise continue the second step here.
        if (result?.access_token) return finishSignIn(result.access_token, returnTo);
        if (result) setChallenge(result);
        setResuming(false);
      })
      .catch((err) => { setError(err); setResuming(false); });
  }, []);

  if (resuming) {
    return (
      <div className="min-h-screen flex items-center justify-center bg-background">
        <Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
      </div>
    );
  }
  return (
    <MfaScreen>
      {managing ? <MfaManage session={managing} returnTo={returnTo} />
        : challenge ? <MfaFlow challenge={challenge} returnTo={returnTo} onManage={setManaging} />
        : <ConfirmIdentity returnTo={returnTo} onChallenge={setChallenge} initialError={error} />}
    </MfaScreen>
  );
}

// Changing two-factor settings starts with a fresh sign-in, then a code from an enrolled method.
function ConfirmIdentity({ returnTo, onChallenge, initialError }) {
  const info = useAppInfo();
  const options = info ? info.auth_config || {} : null;
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(initialError);
  const [busy, setBusy] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError(null);
    setBusy(true);
    try {
      onChallenge(await signInToManageMfa(email, password));
    } catch (err) {
      setError(err);
      setBusy(false);
    }
  };

  const withProvider = (provider) => signInWithProvider(provider, returnTo, { manage: true }).catch(setError);
  const providers = options ? PROVIDERS.filter((provider) => options[provider.flag] ?? provider.id === "google") : [];

  return (
    <>
      <MfaHeader title={info && `Welcome to ${info.name || "the app"}`} description="Sign in to continue" />
      <MfaNotice error={error} />
      {!options && !error && <Loader2 className="mx-auto w-6 h-6 animate-spin text-muted-foreground" />}
      {options && (
        <div className="space-y-4">
          {providers.map((provider) => (
            <Button key={provider.id} variant="outline" className="w-full h-12 text-sm font-medium" onClick={() => withProvider(provider.id)}>
              {provider.id === "google" && <GoogleIcon className="w-5 h-5 mr-2" />}
              Continue with {provider.name}
            </Button>
          ))}
          {(options.enable_sso_login || options.use_workspace_sso) && (
            <Button variant="outline" className="w-full h-12 text-sm font-medium" onClick={() => withProvider("sso")}>
              Continue with SSO
            </Button>
          )}
          {options.enable_username_password && (
            <form onSubmit={submit} className="space-y-4">
              <div className="space-y-2">
                <Label htmlFor="mfa-email">Email</Label>
                <div className="relative">
                  <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
                  <Input id="mfa-email" type="email" autoComplete="email" placeholder="you@example.com" value={email}
                    onChange={(e) => setEmail(e.target.value)} className="pl-10 h-12" required />
                </div>
              </div>
              <div className="space-y-2">
                <Label htmlFor="mfa-password">Password</Label>
                <div className="relative">
                  <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
                  <Input id="mfa-password" type="password" autoComplete="current-password" placeholder="••••••••" value={password}
                    onChange={(e) => setPassword(e.target.value)} className="pl-10 h-12" required />
                </div>
              </div>
              <Button type="submit" className="w-full h-12 font-medium" disabled={busy}>
                {busy && <Loader2 className="w-4 h-4 mr-2 animate-spin" />}
                Continue
              </Button>
            </form>
          )}
        </div>
      )}
    </>
  );
}

```

---

## `src/pages/MyCitations.jsx`

```javascript
import { useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useSeo } from '@/hooks/useSeo';
import { useToast } from '@/components/ui/use-toast';
import CitationCard from '@/components/CitationCard';
import EditCitationDialog from '@/components/EditCitationDialog';
import DrawerSelect from '@/components/DrawerSelect';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { GraduationCap, Plus, Quote, Search, Pencil } from 'lucide-react';

const SORTS = [
  { value: 'recent', label: 'Most recent' },
  { value: 'title', label: 'Title A–Z' },
  { value: 'year', label: 'Year (newest)' },
  { value: 'cited', label: 'Most cited' },
];

export default function MyCitations() {
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [papers, setPapers] = useState([]);
  const [citations, setCitations] = useState({});
  const [loading, setLoading] = useState(true);
  const [query, setQuery] = useState('');
  const [field, setField] = useState('all');
  const [sort, setSort] = useState('recent');
  const [editing, setEditing] = useState(null);

  useSeo({
    title: 'My Citations — Chapterly',
    description: 'View, edit, and organize formal citation blocks for your published research papers on Chapterly.',
    url: '/dashboard/citations',
  });

  useEffect(() => {
    if (!user) { setLoading(false); return; }
    let active = true;
    (async () => {
      try {
        const all = await base44.entities.ResearchPaper.filter({ created_by_id: user.id }, '-created_date');
        const published = all.filter((p) => p.status === 'published' && p.citation_id);
        if (active) setPapers(published);
        const cites = await base44.entities.Citation.filter({}).catch(() => []);
        if (active) {
          const map = {};
          cites.forEach((c) => { map[c.cited_paper_id] = (map[c.cited_paper_id] || 0) + 1; });
          setCitations(map);
        }
      } catch {
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  const fields = useMemo(() => {
    const set = new Set(papers.map((p) => p.field || 'Other'));
    return ['all', ...Array.from(set)];
  }, [papers]);

  const filtered = useMemo(() => {
    let list = papers.slice();
    if (field !== 'all') list = list.filter((p) => (p.field || 'Other') === field);
    if (query.trim()) {
      const q = query.toLowerCase();
      list = list.filter((p) =>
        p.title.toLowerCase().includes(q) ||
        (p.authors || []).join(',').toLowerCase().includes(q) ||
        (p.citation_id || '').toLowerCase().includes(q)
      );
    }
    list.sort((a, b) => {
      if (sort === 'title') return a.title.localeCompare(b.title);
      if (sort === 'year') return new Date(b.published_date || 0) - new Date(a.published_date || 0);
      if (sort === 'cited') return (citations[b.id] || 0) - (citations[a.id] || 0);
      return new Date(b.created_date || 0) - new Date(a.created_date || 0);
    });
    return list;
  }, [papers, field, query, sort, citations]);

  const onSaved = (updated) => {
    setPapers((prev) => prev.map((p) => (p.id === updated.id ? updated : p)));
    toast({ title: 'Citation updated' });
  };

  return (
    <div className="space-y-8">
      <div className="flex items-start justify-between gap-4 flex-wrap">
        <div>
          <h1 className="font-heading text-3xl font-semibold tracking-tight flex items-center gap-2">
            <Quote className="w-7 h-7" /> My citations
          </h1>
          <p className="text-muted-foreground text-sm mt-1 max-w-xl">
            View, edit, and organize formal citation blocks for your published papers — download as PNG or PDF, or copy an embeddable snippet.
          </p>
        </div>
        <Link to="/dashboard/research/new">
          <Button className="rounded-full">
            <Plus className="w-4 h-4 mr-1.5" /> New paper
          </Button>
        </Link>
      </div>

      {loading ? (
        <p className="text-muted-foreground text-sm">Loading your citations…</p>
      ) : papers.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-border p-12 text-center">
          <GraduationCap className="w-8 h-8 mx-auto text-muted-foreground" />
          <p className="mt-3 text-sm text-muted-foreground">You have no published papers with citations yet.</p>
          <Link to="/dashboard/research/new">
            <Button className="rounded-full mt-4">Publish a paper</Button>
          </Link>
        </div>
      ) : (
        <>
          <div className="flex flex-col sm:flex-row gap-3">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
              <Input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search title, author, or citation ID" className="pl-9 rounded-full" />
            </div>
            <div className="sm:w-48">
              <DrawerSelect label="Field" value={field} options={fields.map((f) => ({ value: f, label: f === 'all' ? 'All fields' : f }))} onChange={setField} />
            </div>
            <div className="sm:w-44">
              <DrawerSelect label="Sort by" value={sort} options={SORTS} onChange={setSort} />
            </div>
          </div>

          <div className="text-xs text-muted-foreground">{filtered.length} of {papers.length} citations</div>

          <div className="space-y-8">
            {filtered.map((p) => (
              <div key={p.id} className="space-y-2">
                <div className="flex items-center gap-2 text-xs text-muted-foreground">
                  <span className="font-mono">{p.citation_id}</span>
                  <span>·</span>
                  <span className="inline-flex items-center gap-1"><Quote className="w-3 h-3" /> {citations[p.id] || 0} cited</span>
                  <Button variant="ghost" size="sm" className="ml-auto h-7 px-2 text-xs rounded-full" onClick={() => setEditing(p)}>
                    <Pencil className="w-3 h-3 mr-1" /> Edit
                  </Button>
                </div>
                <CitationCard paper={p} />
              </div>
            ))}
            {filtered.length === 0 && <p className="text-sm text-muted-foreground">No citations match your filters.</p>}
          </div>
        </>
      )}

      <EditCitationDialog paper={editing} open={!!editing} onOpenChange={(o) => !o && setEditing(null)} onSaved={onSaved} />
    </div>
  );
}
```

---

## `src/pages/OAuthConsent.jsx`

```javascript
import React, { useEffect, useState } from "react";
import { appParams } from "@/lib/app-params";
import { Button } from "@/components/ui/button";
import { ShieldCheck, Loader2 } from "lucide-react";
import AuthLayout from "@/components/AuthLayout";

// App-side OAuth consent page for the app's MCP server. The platform redirects
// AI clients here (see base44/mcp/config.json `consent_path`) with an opaque
// `ctx` handle — the authorization request itself lives on the server. This page
// gates on the app-user session, fetches the display info for that handle, shows
// the categories of access being granted, and posts the approve/deny decision.
// Do not change the fetch calls, headers, or the `ctx` handle handling — styling
// and copy are safe to edit.
export default function OAuthConsent() {
  const ctx = new URLSearchParams(window.location.search).get("ctx");
  const [info, setInfo] = useState(null);
  const [checking, setChecking] = useState(true);
  const [submitting, setSubmitting] = useState(false);
  const [decided, setDecided] = useState("");
  const [error, setError] = useState("");
  const [reconnect, setReconnect] = useState("");

  useEffect(() => {
    (async () => {
      let redirecting = false;
      try {
        if (!ctx) {
          setError("This authorization link is invalid or has expired.");
          return;
        }
        // Resolve the handle first: a dead handle must never render
        // approve/deny, and the response carries the app's configured login
        // route for the signed-out redirect below. Send the session (cookie +
        // bearer token) so the server can list the granted tools for a
        // signed-in user — the same auth the approve/deny call sends; without
        // it the display request is anonymous and shows no tools.
        const infoHeaders = {};
        if (appParams.token) infoHeaders.Authorization = "Bearer " + appParams.token;
        const res = await fetch(
          `/api/apps/${appParams.appId}/mcp/consent-info?handle=${encodeURIComponent(ctx)}`,
          { credentials: "include", headers: infoHeaders },
        );
        if (!res.ok) {
          setError("This authorization link is invalid or has expired.");
          return;
        }
        const data = await res.json();
        // Gate on the server's auth result, NOT base44.auth.isAuthenticated():
        // the SDK check runs the bearer path, so a cookie-only session (platform
        // login/SSO, or a private app with a stale localStorage token) would read
        // as signed-out and redirect — even though /consent-info just
        // authenticated this same request via its cookie fallback. data.authenticated
        // keeps the redirect decision in agreement with what the server returned.
        if (!data.authenticated) {
          // The short handle rides back in returnTo; login_path is
          // owner-configured and validated server-side as a same-origin path.
          // Send from_url too: a custom-auth app coerced to platform auth (e.g.
          // public_without_login under workspace SSO) serves the platform login,
          // which honors from_url rather than returnTo. Rebuild the query from
          // `ctx` alone — never forward window.location.search raw: the platform
          // resume returns from_url verbatim, so crafted extras on the consent
          // link (app_base_url, access_token, …) would ride through the login
          // round-trip and app-params.js would persist them into the freshly
          // authenticated session.
          const returnTo =
            window.location.pathname + "?ctx=" + encodeURIComponent(ctx);
          const encoded = encodeURIComponent(returnTo);
          redirecting = true; // keep the spinner while the browser navigates
          window.location.href =
            (data.login_path || "/login") + "?returnTo=" + encoded + "&from_url=" + encoded;
          return;
        }
        setInfo(data);
      } catch (e) {
        setError("Could not load this authorization request. Please try again.");
      } finally {
        if (!redirecting) setChecking(false);
      }
    })();
  }, [ctx]);

  const respond = async (action) => {
    setSubmitting(true);
    setError("");
    try {
      const headers = { "Content-Type": "application/json" };
      // Cookie-backed sessions carry no token; sending "Bearer null" would
      // shadow the valid cookie, so add the header only when a token exists.
      if (appParams.token) headers.Authorization = "Bearer " + appParams.token;
      const res = await fetch(`/api/apps/${appParams.appId}/mcp/authorize-grant`, {
        method: "POST",
        credentials: "include",
        headers,
        body: JSON.stringify({ ctx, action }),
      });
      if (!res.ok) {
        // 401 = the session expired before the (single-use, still-unconsumed)
        // handle was spent; retrying the same controls re-sends the dead session
        // forever. Send the user back through login preserving `ctx` — the same
        // redirect the initial signed-out path uses — so they can return and
        // approve the still-valid handle.
        if (res.status === 401) {
          const returnTo = window.location.pathname + "?ctx=" + encodeURIComponent(ctx);
          const encoded = encodeURIComponent(returnTo);
          window.location.href =
            ((info && info.login_path) || "/login") + "?returnTo=" + encoded + "&from_url=" + encoded;
          return;
        }
        // These all come AFTER the single-use handle is atomically consumed
        // (409 tool set changed; 403 host/resource/app mismatch; 404 access
        // gone; 400 malformed/handle already used), so retrying can only 404.
        // Show a terminal reconnect state, not an impossible "try again".
        if ([400, 403, 404, 409].includes(res.status)) {
          let detail = "";
          try { detail = (await res.json()).detail; } catch (_) { /* keep default */ }
          setReconnect(detail || "This authorization can no longer be completed. Reconnect from your AI client to try again.");
          setSubmitting(false);
          return;
        }
        throw new Error("Could not complete authorization. Please try again.");
      }
      const data = await res.json();
      window.location.href = data.redirect_url;
      if (!/^https?:/i.test(data.redirect_url)) {
        // Custom-scheme redirect (native AI clients, e.g. cursor://): browsers
        // may block or not visibly navigate, so show a terminal state instead
        // of an eternal spinner.
        setDecided(action);
        setSubmitting(false);
      }
    } catch (e) {
      setError(e.message);
      setSubmitting(false);
    }
  };

  if (checking) {
    return (
      <AuthLayout icon={ShieldCheck} title="Authorize access">
        <div className="flex items-center justify-center py-6 text-muted-foreground">
          <Loader2 className="w-5 h-5 mr-2 animate-spin" aria-hidden="true" />
          Loading…
        </div>
      </AuthLayout>
    );
  }

  const client = (info && info.client_name) || "An AI client";
  const appName = (info && info.app_name) || "this app";

  if (decided) {
    return (
      <AuthLayout
        icon={ShieldCheck}
        title={decided === "approve" ? "Access granted" : "Access denied"}
        subtitle={`You can return to ${client} and close this window.`}
      />
    );
  }

  // Terminal: the authorization request is no longer valid (tool set changed +
  // handle consumed). Retrying can't succeed, so show reconnect guidance with
  // no approve/deny controls.
  if (reconnect) {
    return (
      <AuthLayout icon={ShieldCheck} title="Reconnect required">
        <div className="p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
          {reconnect}
        </div>
      </AuthLayout>
    );
  }

  // No consent details means nothing trustworthy to approve: a failed
  // consent-info load (expired handle, rate limit, transient error) renders
  // the error alone, never the approve/deny controls.
  if (error && !info) {
    return (
      <AuthLayout icon={ShieldCheck} title="Authorize access">
        <div className="p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
          {error}
        </div>
      </AuthLayout>
    );
  }

  const tools = Array.isArray(info.tools) ? info.tools : [];

  return (
    <AuthLayout
      icon={ShieldCheck}
      title="Authorize access"
      subtitle={`${client} wants to access ${appName} on your behalf`}
    >
      {error && (
        <div className="mb-4 p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
          {error}
        </div>
      )}

      <p className="text-sm font-medium text-foreground mb-2">
        {tools.length ? `It will be able to use these tools in ${appName}:` : "No tools requested"}
      </p>
      {tools.length > 0 && (
        <ul className="space-y-2 text-sm mb-6">
          {tools.map((tool) => (
            <li key={tool.name} className="flex flex-col">
              <span className="text-foreground font-medium">
                {tool.title || tool.name}
              </span>
              {tool.description && (
                <span className="text-muted-foreground">{tool.description}</span>
              )}
            </li>
          ))}
        </ul>
      )}

      <div className="flex gap-3">
        <Button
          variant="outline"
          className="flex-1 h-12 font-medium"
          disabled={submitting}
          onClick={() => respond("deny")}
        >
          Deny
        </Button>
        <Button
          className="flex-1 h-12 font-medium"
          disabled={submitting}
          onClick={() => respond("approve")}
        >
          {submitting ? <Loader2 className="w-4 h-4 mr-2 animate-spin" /> : null}
          Approve
        </Button>
      </div>
    </AuthLayout>
  );
}

```

---

## `src/pages/Privacy.jsx`

```javascript
import LegalLayout from '@/components/LegalLayout';
import { useSeo } from '@/hooks/useSeo';

export default function Privacy() {
  useSeo({
    title: 'Privacy Policy — Chapterly',
    description: 'How Chapterly collects, uses, and protects your information, and how to delete your account.',
    url: '/privacy',
  });

  return (
    <LegalLayout
      title="Privacy Policy"
      subtitle="This policy explains what information Chapterly collects, why we collect it, and the choices you have."
      updated="November 2026"
    >
      <p>
        Chapterly is a serialized fiction platform where readers discover and support independent writers. This policy
        covers the Chapterly website and the Chapterly mobile apps. By using Chapterly you agree to this policy.
      </p>

      <h2>Information we collect</h2>
      <ul>
        <li><strong>Account details</strong> — your email address, name, profile display name, and profile photo if you add one.</li>
        <li><strong>Content you create</strong> — stories, chapters, covers, comments, ratings, reading lists, research papers, and messages to our AI assistants.</li>
        <li><strong>Activity</strong> — stories you follow, chapters you read, reading progress and goals, likes, and notifications.</li>
        <li><strong>Payments</strong> — records of chapter unlocks, subscriptions, tips, memberships, and payouts, including the amount, date, and payment reference. Card and bank details are entered directly with our payment providers; Chapterly never stores them.</li>
        <li><strong>Technical data</strong> — device type, browser, approximate region, and basic usage events used to keep the service working and secure.</li>
      </ul>

      <h2>How we use it</h2>
      <ul>
        <li>To run your account, deliver content, and show you the stories, writers, and updates you follow.</li>
        <li>To process payments and pay writers their share of sales.</li>
        <li>To provide AI writing and reading tools on the text you submit to them.</li>
        <li>To send you service emails such as password resets, purchase receipts, and, if you opt in, weekly reading digests.</li>
        <li>To keep the platform safe: detecting abuse, spam, and fraud, and reviewing reports.</li>
      </ul>

      <h2>Payments</h2>
      <p>
        Payments are handled by third-party payment providers (including Stripe and SafePay). They process your payment
        details under their own privacy policies. Chapterly receives confirmation of the transaction and the amount, not
        your card number.
      </p>

      <h2>Third-party services</h2>
      <ul>
        <li><strong>Sign-in</strong> — you can create an account with email and password, Google, or Apple. These providers share your name and email address with us.</li>
        <li><strong>AI tools</strong> — text you send to the writing, recap, and assistant features is processed by AI service providers to generate the response you asked for.</li>
        <li><strong>Writer connections</strong> — if you choose to connect Instagram, Gmail, or Slack as a writer, we use those permissions only for the actions you trigger, such as posting your story or receiving activity notifications.</li>
        <li><strong>Email delivery</strong> and <strong>hosting</strong> providers that operate the service on our behalf.</li>
      </ul>

      <h2>Cookies and local storage</h2>
      <p>
        Chapterly uses local storage and cookies to keep you signed in, remember your preferences (such as light or dark
        theme), and measure basic usage. You can clear them in your browser settings; some features may not work if you do.
      </p>

      <h2>Sharing</h2>
      <p>
        We do not sell your personal information. We share it only with the service providers described above, when
        required by law, or to protect the rights and safety of our users. Content you publish — your stories, chapters,
        and public profile — is visible to anyone using Chapterly.
      </p>

      <h2>Your choices and rights</h2>
      <ul>
        <li><strong>Access and correction</strong> — view and edit your profile details at any time.</li>
        <li><strong>Deletion</strong> — delete your account from Profile → Delete account, or follow the steps on the <a href="/support">Support page</a>. This removes your account and personal details.</li>
        <li><strong>Email preferences</strong> — unsubscribe from digests using the link in any digest email.</li>
      </ul>

      <h2>Children</h2>
      <p>
        Chapterly is not intended for children under 13. We do not knowingly collect information from children under 13.
        If you believe a child has created an account, contact us and we will remove it.
      </p>

      <h2>Changes</h2>
      <p>
        We may update this policy as the service evolves. Material changes will be announced in the app, and the date at
        the top of this page will change.
      </p>

      <h2>Contact</h2>
      <p>
        Questions about this policy or your data? Reach the Chapterly team at{' '}
        <a href="mailto:mariamalik13397@gmail.com">mariamalik13397@gmail.com</a>.
      </p>
    </LegalLayout>
  );
}
```

---

## `src/pages/Profile.jsx`

```javascript
import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Image } from '@/components/ui/image';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { useToast } from '@/components/ui/use-toast';
import StoryCard from '@/components/StoryCard';
import PurchaseHistory from '@/components/PurchaseHistory';
import WriterEarningsDashboard from '@/components/WriterEarningsDashboard';
import { UserPlus, UserCheck, Pencil, BookOpen, Trash2 } from 'lucide-react';
import TipButton from '@/components/TipButton';
import ReadingGoalTracker from '@/components/ReadingGoalTracker';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
import { useSeo } from '@/hooks/useSeo';
import { getPublicProfile } from '@/lib/publicProfiles';

export default function Profile() {
  const { userId } = useParams();
  const { user: me, refresh } = useCurrentUser();
  const { toast } = useToast();
  const [profile, setProfile] = useState(null);
  const [stories, setStories] = useState([]);
  const [following, setFollowing] = useState(false);
  const [followerCount, setFollowerCount] = useState(0);
  const [followingList, setFollowingList] = useState([]);
  const [library, setLibrary] = useState([]);
  const [savedStories, setSavedStories] = useState([]);
  const [savedPapers, setSavedPapers] = useState([]);
  const [editMode, setEditMode] = useState(false);
  const [form, setForm] = useState({ display_name: '', bio: '', avatar_url: '' });
  const [deleting, setDeleting] = useState(false);

  const targetId = userId || me?.id;
  const isMe = !userId || (me && userId === me.id);

  const profileName = profile ? (profile.display_name || profile.full_name || 'Anonymous') : null;
  useSeo({
    title: profile ? `${profileName} — Writer on Chapterly` : undefined,
    description: profile
      ? (profile.bio || `Read original serialized fiction by ${profileName} on Chapterly.`).slice(0, 160)
      : undefined,
    image: profile?.avatar_url,
    url: targetId ? `/profile/${targetId}` : '/profile',
    jsonLd: profile
      ? {
          '@context': 'https://schema.org',
          '@type': 'Person',
          name: profileName,
          description: profile.bio || undefined,
          url: `https://chapterly.ariamalik.com/profile/${targetId}`,
        }
      : undefined,
  });

  useEffect(() => {
    if (!targetId) return;
    let active = true;
    (async () => {
      try {
        const u = await getPublicProfile(targetId);
        if (!active) return;
        setProfile(u);
        setForm({ display_name: u.display_name || u.full_name || '', bio: u.bio || '', avatar_url: u.avatar_url || '' });
        const s = await base44.entities.Story.filter({ created_by_id: targetId, status: 'published' }, '-created_date');
        if (active) setStories(s);
        const fl = await base44.entities.Follow.filter({ writer_id: targetId });
        if (active) setFollowerCount(fl.length);
        if (me && !isMe) {
          const myFollow = await base44.entities.Follow.filter({ follower_id: me.id, writer_id: targetId });
          if (active) setFollowing(myFollow.length > 0);
        }
        if (isMe && me) {
          const myFollows = await base44.entities.Follow.filter({ follower_id: me.id });
          if (active) setFollowingList(myFollows);
          const purchases = await base44.entities.Purchase.filter({ reader_id: me.id });
          const subs = await base44.entities.Subscription.filter({ reader_id: me.id, status: 'active' });
          // accessible chapters: purchased + any from subscribed authors
          const lib = [];
          for (const p of purchases) {
            try { const c = await base44.entities.Chapter.get(p.chapter_id); lib.push(c); } catch {}
          }
          for (const sub of subs) {
            const authorStories = await base44.entities.Story.filter({ created_by_id: sub.writer_id, status: 'published' });
            for (const s of authorStories) {
              const ch = await base44.entities.Chapter.filter({ story_id: s.id, published: true, status: 'paid' });
              ch.forEach((c) => !lib.find((x) => x.id === c.id) && lib.push(c));
            }
          }
          if (active) setLibrary(lib);
          const saved = await base44.entities.ReadingList.filter({ user_id: me.id });
          const sStories = [];
          const sPapers = [];
          for (const sv of saved) {
            try {
              if (sv.target_type === 'paper') {
                const p = await base44.entities.ResearchPaper.get(sv.target_id);
                if (p && p.status === 'published') sPapers.push(p);
              } else {
                const st = await base44.entities.Story.get(sv.target_id);
                if (st && st.status === 'published') sStories.push(st);
              }
            } catch {}
          }
          if (active) { setSavedStories(sStories); setSavedPapers(sPapers); }
        }
      } catch {}
    })();
    return () => { active = false; };
  }, [targetId, me, isMe]);

  const toggleFollow = async () => {
    if (!me) return toast({ title: 'Sign in to follow' });
    if (following) {
      const ex = await base44.entities.Follow.filter({ follower_id: me.id, writer_id: targetId });
      if (ex[0]) await base44.entities.Follow.delete(ex[0].id);
      setFollowing(false); setFollowerCount((c) => c - 1);
    } else {
      await base44.entities.Follow.create({ follower_id: me.id, writer_id: targetId });
      setFollowing(true); setFollowerCount((c) => c + 1);
    }
  };

  const saveProfile = async () => {
    try {
      await base44.auth.updateMe({ display_name: form.display_name, bio: form.bio, avatar_url: form.avatar_url });
      setEditMode(false);
      refresh();
      setProfile((p) => ({ ...p, ...form }));
      toast({ title: 'Profile updated' });
    } catch (e) {
      toast({ title: 'Update failed', description: String(e), variant: 'destructive' });
    }
  };

  const deleteAccount = async () => {
    setDeleting(true);
    try {
      await base44.functions.invoke('deleteAccount', {});
      await base44.auth.logout();
      window.location.href = '/';
    } catch (e) {
      setDeleting(false);
      toast({ title: 'Deletion failed', description: e.message, variant: 'destructive' });
    }
  };

  const onAvatar = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    const { file_url } = await base44.integrations.Core.UploadFile({ file });
    setForm((f) => ({ ...f, avatar_url: file_url }));
  };

  if (!profile) return <p className="text-muted-foreground text-sm">Loading profile…</p>;

  return (
    <div className="space-y-10">
      <div className="flex items-start gap-5">
        <Avatar className="w-20 h-20">
          <AvatarImage src={profile.avatar_url} />
          <AvatarFallback className="text-2xl">{(profile.display_name || profile.full_name || '?')[0]}</AvatarFallback>
        </Avatar>
        <div className="flex-1">
          <h1 className="font-heading text-2xl font-semibold">{profile.display_name || profile.full_name || 'Anonymous'}</h1>
          <p className="text-sm text-muted-foreground mt-1 max-w-lg whitespace-pre-wrap">{profile.bio || 'No bio yet.'}</p>
          <div className="mt-3 flex items-center gap-4">
            <span className="text-sm text-muted-foreground">{followerCount} followers</span>
            {isMe ? (
              <Button variant="outline" size="sm" className="rounded-full" onClick={() => setEditMode((v) => !v)}>
                <Pencil className="w-3.5 h-3.5 mr-1.5" /> Edit profile
              </Button>
            ) : (
              <Button onClick={toggleFollow} variant={following ? 'outline' : 'default'} size="sm" className="rounded-full">
                {following ? <UserCheck className="w-4 h-4 mr-1.5" /> : <UserPlus className="w-4 h-4 mr-1.5" />}
                {following ? 'Following' : 'Follow'}
              </Button>
            )}
            {!isMe && <TipButton writerId={targetId} writerName={profile.display_name || profile.full_name} />}
          </div>
        </div>
      </div>

      {isMe && editMode && (
        <div className="rounded-xl border border-border/60 p-5 space-y-4">
          <h2 className="font-heading text-lg font-semibold">Edit profile</h2>
          <div className="flex items-center gap-4">
            <Avatar className="w-16 h-16">
              <AvatarImage src={form.avatar_url} />
              <AvatarFallback>{(form.display_name || '?')[0]}</AvatarFallback>
            </Avatar>
            <label className="text-sm underline underline-offset-2 cursor-pointer">
              Upload avatar
              <input type="file" accept="image/*" className="hidden" onChange={onAvatar} />
            </label>
          </div>
          <div>
            <Label>Display name</Label>
            <Input value={form.display_name} onChange={(e) => setForm({ ...form, display_name: e.target.value })} className="mt-1.5" />
          </div>
          <div>
            <Label>Bio</Label>
            <Textarea value={form.bio} onChange={(e) => setForm({ ...form, bio: e.target.value })} rows={3} className="mt-1.5" />
          </div>
          <Button onClick={saveProfile} className="rounded-full">Save</Button>
          <div className="pt-4 border-t border-border/60">
            <AlertDialog>
              <AlertDialogTrigger asChild>
                <Button variant="outline" className="rounded-full text-destructive border-destructive/30 hover:bg-destructive/10">
                  <Trash2 className="w-4 h-4 mr-1.5" /> Delete account
                </Button>
              </AlertDialogTrigger>
              <AlertDialogContent>
                <AlertDialogHeader>
                  <AlertDialogTitle>Delete your account?</AlertDialogTitle>
                  <AlertDialogDescription>
                    This permanently removes your profile, stories, chapters, and all associated data. This action cannot be undone.
                  </AlertDialogDescription>
                </AlertDialogHeader>
                <AlertDialogFooter>
                  <AlertDialogCancel>Cancel</AlertDialogCancel>
                  <AlertDialogAction
                    onClick={deleteAccount}
                    disabled={deleting}
                    className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
                  >
                    {deleting ? 'Deleting…' : 'Delete permanently'}
                  </AlertDialogAction>
                </AlertDialogFooter>
              </AlertDialogContent>
            </AlertDialog>
          </div>
        </div>
      )}

      <section>
        <h2 className="font-heading text-xl font-semibold mb-4">Stories</h2>
        {stories.length === 0 ? (
          <p className="text-sm text-muted-foreground">
            {isMe ? <>No published stories yet. <Link to="/dashboard" className="underline">Start writing</Link>.</> : 'No published stories.'}
          </p>
        ) : (
          <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-5">
            {stories.map((s) => <StoryCard key={s.id} story={s} />)}
          </div>
        )}
      </section>

      {isMe && (
        <>
          <ReadingGoalTracker />

          <WriterEarningsDashboard />

          <section>
            <h2 className="font-heading text-xl font-semibold mb-4">Library ({library.length})</h2>
            {library.length === 0 ? (
              <p className="text-sm text-muted-foreground">Chapters you unlock or subscribe to will appear here.</p>
            ) : (
              <div className="grid sm:grid-cols-2 gap-3">
                {library.map((c) => (
                  <Link key={c.id} to={`/read/${c.id}`} className="block rounded-xl border border-border/60 p-4 hover:bg-muted/40 transition">
                    <p className="text-xs text-muted-foreground">Unlocked chapter</p>
                    <p className="font-medium text-sm mt-1">{c.title}</p>
                  </Link>
                ))}
              </div>
            )}
          </section>

          <PurchaseHistory />

          <section>
            <h2 className="font-heading text-xl font-semibold mb-4">Reading list ({savedStories.length + savedPapers.length})</h2>
            {savedStories.length === 0 && savedPapers.length === 0 ? (
              <p className="text-sm text-muted-foreground">Stories and papers you save to read later will appear here.</p>
            ) : (
              <div className="space-y-6">
                {savedStories.length > 0 && (
                  <div>
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground mb-3">Stories</p>
                    <div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-5">
                      {savedStories.map((s) => <StoryCard key={s.id} story={s} />)}
                    </div>
                  </div>
                )}
                {savedPapers.length > 0 && (
                  <div>
                    <p className="text-[11px] uppercase tracking-wide text-muted-foreground mb-3">Research papers</p>
                    <div className="grid sm:grid-cols-2 gap-3">
                      {savedPapers.map((p) => (
                        <Link key={p.id} to={`/research/${p.id}`} className="block rounded-xl border border-border/60 p-4 hover:bg-muted/40 transition">
                          <p className="font-medium text-sm">{p.title}</p>
                          <p className="text-xs text-muted-foreground mt-1">{p.field || 'Research'}{(p.authors || []).length ? ` · ${p.authors.join(', ')}` : ''}</p>
                        </Link>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            )}
          </section>

          <section>
            <h2 className="font-heading text-xl font-semibold mb-4">Following ({followingList.length})</h2>
            {followingList.length === 0 ? (
              <p className="text-sm text-muted-foreground">Follow writers to see their new chapters in your feed.</p>
            ) : (
              <div className="flex flex-wrap gap-2">
                {followingList.map((f) => (
                  <Link key={f.id} to={`/profile/${f.writer_id}`} className="inline-flex items-center gap-1.5 text-sm px-3 py-1.5 rounded-full border border-border hover:bg-muted">
                    <BookOpen className="w-3.5 h-3.5" /> View writer
                  </Link>
                ))}
              </div>
            )}
          </section>
        </>
      )}
    </div>
  );
}
```

---

## `src/pages/ReadChapter.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/components/ui/use-toast';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import Paywall from '@/components/Paywall';
import TipButton from '@/components/TipButton';
import ReportButton from '@/components/ReportButton';
import ShareButtons from '@/components/ShareButtons';
import { Heart, ArrowLeft, ArrowRight, MessageSquare, Send, Clock, Trash2, Sparkles } from 'lucide-react';
import DOMPurify from 'dompurify';
import { useSeo } from '@/hooks/useSeo';
import { getPublicProfile, getPublicProfiles } from '@/lib/publicProfiles';

export default function ReadChapter() {
  const { chapterId } = useParams();
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [chapter, setChapter] = useState(null);
  const [story, setStory] = useState(null);
  const [author, setAuthor] = useState(null);
  const [access, setAccess] = useState(false);
  const [body, setBody] = useState('');
  const [checking, setChecking] = useState(true);
  const [comments, setComments] = useState([]);
  const [commenters, setCommenters] = useState({});
  const [draft, setDraft] = useState('');
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(0);
  const [allChapters, setAllChapters] = useState([]);
  const [pendingManual, setPendingManual] = useState(false);
  const [bankDetails, setBankDetails] = useState('');

  const authorName = author ? (author.display_name || author.full_name) : null;
  useSeo({
    title: chapter && story ? `${chapter.title} — ${story.title}` : undefined,
    description: chapter && story
      ? `${story.description || story.title} — Chapter: ${chapter.title}. Read serialized fiction on Chapterly.`
      : undefined,
    image: story?.cover_url,
    url: `/read/${chapterId}`,
    jsonLd: chapter && story
      ? {
          '@context': 'https://schema.org',
          '@type': 'Article',
          headline: chapter.title,
          articleSection: story.title,
          author: authorName ? { '@type': 'Person', name: authorName } : undefined,
          isPartOf: { '@type': 'Book', name: story.title },
          url: `https://chapterly.ariamalik.com/read/${chapterId}`,
        }
      : undefined,
  });

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const c = await base44.entities.Chapter.get(chapterId);
        if (!active) return;
        setChapter(c);
        if (!c.published) { setChecking(false); return; }
        const s = await base44.entities.Story.get(c.story_id);
        if (!active) return;
        setStory(s);
        getPublicProfile(s.created_by_id).then(setAuthor).catch(() => {});
        base44.entities.Setting.filter({ key: 'bank_instructions' }).then((r) => { if (active && r[0]) setBankDetails(r[0].value); }).catch(() => {});
        const all = await base44.entities.Chapter.filter({ story_id: s.id, published: true }, 'order_index');
        if (active) setAllChapters(all);

        // access — paid bodies are gated by the backend, never by this browser check
        if (c.status === 'free') {
          setBody(c.body || '');
          setAccess(true);
          setChecking(false);
        } else {
          const res = await base44.functions.invoke('getChapterContent', { chapterId: c.id });
          if (!active) return;
          const data = res.data || {};
          setBody(data.body || '');
          setAccess(!data.locked);
          setChecking(false);
          if (data.locked && user) {
            const pending = await base44.entities.ManualPayment.filter({ reader_id: user.id, chapter_id: c.id, status: 'pending' });
            if (active) setPendingManual(pending.length > 0);
          }
        }

        // comments
        const cms = await base44.entities.Comment.filter({ chapter_id: c.id }, '-created_date');
        if (active) setComments(cms);
        const uids = [...new Set(cms.map((m) => m.user_id))];
        const map = await getPublicProfiles(uids);
        if (active) setCommenters(map);

        // likes
        const likes = await base44.entities.Like.filter({ target_type: 'chapter', target_id: c.id });
        if (active) setLikeCount(likes.length);
        if (user) {
          const myLike = await base44.entities.Like.filter({ user_id: user.id, target_type: 'chapter', target_id: c.id });
          if (active) setLiked(myLike.length > 0);
        }
      } catch {
        if (active) setChapter(null);
      }
    })();
    return () => { active = false; };
  }, [chapterId, user]);

  useEffect(() => {
    if (!chapter || !user || access || checking) return;
    const params = new URLSearchParams(window.location.search);
    const justPaid = params.get('paid') === '1' || params.get('subscribed') === '1' || params.get('safepay') === '1';
    if (!justPaid) return;
    let attempts = 0;
    const id = setInterval(async () => {
      attempts++;
      try {
        const res = await base44.functions.invoke('getChapterContent', { chapterId: chapter.id });
        const data = res.data || {};
        if (!data.locked && data.body) {
          setBody(data.body);
          setAccess(true);
          clearInterval(id);
          toast({ title: 'Access granted', description: 'Enjoy the story.' });
        } else if (attempts >= 8) {
          clearInterval(id);
          toast({ title: 'Still confirming payment', description: 'Refresh in a moment to access this chapter.' });
        }
      } catch {}
    }, 1500);
    return () => clearInterval(id);
  }, [chapter, user, access, checking, story]);

  const viewed = useRef(false);
  const completed = useRef(false);
  const sentinelRef = useRef(null);
  useEffect(() => {
    if (!chapter || !access || viewed.current) return;
    viewed.current = true;
    base44.functions.invoke('incrementChapterView', { chapterId: chapter.id }).catch(() => {});
    base44.analytics.track({ eventName: 'chapter_read', properties: { chapter_id: chapter.id, story_id: chapter.story_id } });
    if (user) {
      const today = new Date().toISOString().slice(0, 10);
      const wc = chapter.word_count || ((body || '').replace(/<[^>]+>/g, ' ').trim().split(/\s+/).filter(Boolean).length);
      base44.entities.ReadingProgress.filter({ user_id: user.id, date: today, chapter_id: chapter.id })
        .then((existing) => {
          if (!existing.length) {
            base44.entities.ReadingProgress.create({ user_id: user.id, date: today, chapter_id: chapter.id, word_count: wc }).catch(() => {});
          }
        }).catch(() => {});
    }
  }, [chapter, access]);

  useEffect(() => {
    if (!chapter || !access || completed.current) return;
    const sentinel = sentinelRef.current;
    if (!sentinel) return;
    const obs = new IntersectionObserver((entries) => {
      if (entries[0]?.isIntersecting && !completed.current) {
        completed.current = true;
        base44.functions.invoke('logChapterCompletion', { chapterId: chapter.id }).catch(() => {});
        obs.disconnect();
      }
    }, { threshold: 0.5 });
    obs.observe(sentinel);
    return () => obs.disconnect();
  }, [chapter, access]);

  const startCheckout = async (type) => {
    if (!user) return toast({ title: 'Sign in to continue' });
    if (window.self !== window.top) {
      toast({ title: 'Checkout unavailable', description: 'Open the published app to complete payment.', variant: 'destructive' });
      return;
    }
    try {
      const payload = { type };
      if (type === 'chapter') payload.chapterId = chapter.id;
      else payload.writerId = story.created_by_id;
      const res = await base44.functions.invoke('createCheckout', payload);
      if (res.data?.url) {
        window.location.href = res.data.url;
      } else {
        toast({ title: 'Checkout failed', description: res.data?.error || 'No checkout URL returned', variant: 'destructive' });
      }
    } catch (e) {
      toast({ title: 'Checkout failed', description: e.message, variant: 'destructive' });
    }
  };

  const unlock = () => startCheckout('chapter');
  const subscribe = () => startCheckout('subscription');

  const submitManualPayment = async (reference) => {
    if (!user) return toast({ title: 'Sign in to continue' });
    try {
      await base44.entities.ManualPayment.create({ reader_id: user.id, writer_id: story.created_by_id, chapter_id: chapter.id, amount: chapter.price, reference, status: 'pending' });
      setPendingManual(true);
      toast({ title: 'Payment submitted', description: 'Your bank transfer is pending verification.' });
    } catch (e) {
      toast({ title: 'Submission failed', description: e.message, variant: 'destructive' });
    }
  };

  const safepayCheckout = async () => {
    if (!user) return toast({ title: 'Sign in to continue' });
    if (window.self !== window.top) {
      toast({ title: 'Checkout unavailable', description: 'Open the published app to complete payment.', variant: 'destructive' });
      return;
    }
    try {
      const res = await base44.functions.invoke('createSafepayCheckout', { chapterId: chapter.id });
      if (res.data?.url) window.location.href = res.data.url;
      else toast({ title: 'Checkout failed', description: res.data?.error || 'No checkout URL returned', variant: 'destructive' });
    } catch (e) {
      toast({ title: 'Checkout failed', description: e.message, variant: 'destructive' });
    }
  };

  const toggleLike = async () => {
    if (!user) return toast({ title: 'Sign in to like' });
    const wasLiked = liked;
    setLiked(!wasLiked);
    setLikeCount((c) => c + (wasLiked ? -1 : 1));
    try {
      if (wasLiked) {
        const ex = await base44.entities.Like.filter({ user_id: user.id, target_type: 'chapter', target_id: chapter.id });
        if (ex[0]) await base44.entities.Like.delete(ex[0].id);
      } else {
        await base44.entities.Like.create({ user_id: user.id, target_type: 'chapter', target_id: chapter.id });
      }
    } catch {
      setLiked(wasLiked);
      setLikeCount((c) => c + (wasLiked ? 1 : -1));
    }
  };

  const postComment = async () => {
    if (!user) return toast({ title: 'Sign in to comment' });
    const body = draft.trim();
    if (!body) return;
    const c = await base44.entities.Comment.create({ chapter_id: chapter.id, user_id: user.id, body });
    setDraft('');
    setComments((prev) => [c, ...prev]);
    setCommenters((prev) => ({ ...prev, [user.id]: user }));
  };

  const deleteComment = async (commentId) => {
    try {
      await base44.entities.Comment.delete(commentId);
      setComments((prev) => prev.filter((c) => c.id !== commentId));
      toast({ title: 'Comment removed' });
    } catch (e) {
      toast({ title: 'Could not delete', description: e.message, variant: 'destructive' });
    }
  };

  if (chapter === null && checking) return <p className="text-muted-foreground text-sm">Loading chapter…</p>;
  if (!chapter) return <p className="text-muted-foreground text-sm">Chapter not found.</p>;
  if (!chapter.published) return <p className="text-muted-foreground text-sm">This chapter is not published.</p>;
  if (!story) return <p className="text-muted-foreground text-sm">Loading story…</p>;

  const wordCount = chapter.word_count || ((body || '').replace(/<[^>]+>/g, ' ').trim().split(/\s+/).filter(Boolean).length);
  const readMins = Math.max(1, Math.round(wordCount / 200));

  const idx = allChapters.findIndex((c) => c.id === chapter.id);
  const prev = idx > 0 ? allChapters[idx - 1] : null;
  const next = idx >= 0 && idx < allChapters.length - 1 ? allChapters[idx + 1] : null;
  const isAuthor = user && story && user.id === story.created_by_id;

  return (
    <article className="max-w-2xl mx-auto space-y-8">
      <div className="space-y-2">
        <Link to={`/story/${story.id}`} className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
          <ArrowLeft className="w-4 h-4" /> {story.title}
        </Link>
        <h1 className="font-heading text-3xl font-semibold tracking-tight">{chapter.title}</h1>
        <Link to={`/profile/${story.created_by_id}`} className="text-sm text-muted-foreground hover:text-foreground">
          by {author?.display_name || author?.full_name || 'Unknown'}
        </Link>
        <p className="inline-flex items-center gap-1.5 text-xs text-muted-foreground">
          <Clock className="w-3.5 h-3.5" /> {readMins} min read · {wordCount.toLocaleString()} words
        </p>
        <Link to={`/recap/${story.id}?chapter=${chapter.id}`}>
          <Button variant="outline" size="sm" className="rounded-full">
            <Sparkles className="w-4 h-4 mr-1.5" /> Recap so far
          </Button>
        </Link>
        <div className="flex items-center gap-2 pt-1">
          <span className="text-xs text-muted-foreground">Share chapter:</span>
          <ShareButtons
            text={`"${chapter.title}" from ${story.title} on Chapterly`}
            card={{ title: story.title, author: authorName, coverUrl: story.cover_url, genre: story.genre }}
          />
        </div>
      </div>

      {checking ? (
        <p className="text-muted-foreground text-sm">Checking access…</p>
      ) : access ? (
        <>
          <div
            className="prose-folio text-foreground/90 leading-relaxed space-y-4 text-[17px]"
            dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(body || '<p>This chapter has no content yet.</p>') }}
          />
          <div ref={sentinelRef} className="h-1 w-full" aria-hidden="true" />
        </>
      ) : (
        <Paywall chapter={chapter} onUnlock={unlock} onSubscribe={subscribe} subscriptionPrice={story?.subscription_price} onBankPay={submitManualPayment} onSafepay={safepayCheckout} pendingManual={pendingManual} bankDetails={bankDetails} />
      )}

      {access && (
        <div className="flex items-center gap-3 pt-2 border-t border-border/60">
          <Button onClick={toggleLike} variant={liked ? 'default' : 'outline'} size="sm" className="rounded-full">
            <Heart className={`w-4 h-4 mr-1.5 ${liked ? 'fill-current' : ''}`} /> {likeCount}
          </Button>
          <TipButton writerId={story.created_by_id} writerName={authorName} chapterId={chapter.id} />
          <ShareButtons
            url={`${window.location.origin}/story/${story.id}`}
            text={`${story.title} by ${authorName || 'an indie writer'} on Chapterly`}
            className="ml-auto"
            card={{ title: story.title, author: authorName, coverUrl: story.cover_url, genre: story.genre }}
          />
        </div>
      )}

      {(prev || next) && (
        <div className="grid grid-cols-2 gap-3 pt-4 border-t border-border/60">
          {prev ? (
            <Button asChild variant="outline" className="rounded-xl justify-start h-auto py-3">
              <Link to={`/read/${prev.id}`}>
                <ArrowLeft className="w-4 h-4 shrink-0" />
                <span className="flex flex-col items-start text-left min-w-0">
                  <span className="text-[11px] text-muted-foreground">Previous</span>
                  <span className="text-sm font-medium truncate">{prev.title}</span>
                </span>
              </Link>
            </Button>
          ) : <span />}
          {next ? (
            <Button asChild variant="outline" className="rounded-xl justify-end h-auto py-3">
              <Link to={`/read/${next.id}`}>
                <span className="flex flex-col items-end text-right min-w-0">
                  <span className="text-[11px] text-muted-foreground">Next</span>
                  <span className="text-sm font-medium truncate">{next.title}</span>
                </span>
                <ArrowRight className="w-4 h-4 shrink-0" />
              </Link>
            </Button>
          ) : <span />}
        </div>
      )}

      {access && (
        <section className="space-y-4 pt-4">
          <div className="flex items-center justify-between">
            <h2 className="font-heading text-lg font-semibold flex items-center gap-2">
              <MessageSquare className="w-4 h-4" /> Comments ({comments.length})
            </h2>
            <Link to={'/companion/' + story.id + '?chapter=' + chapter.id}>
              <Button variant="outline" size="sm" className="rounded-full">
                <Sparkles className="w-4 h-4 mr-1.5" /> Comment helper
              </Button>
            </Link>
          </div>
          <div className="flex gap-2">
            <Textarea
              value={draft}
              onChange={(e) => setDraft(e.target.value)}
              placeholder="Share your thoughts…"
              className="resize-none"
              rows={2}
            />
            <Button onClick={postComment} size="sm" className="self-end rounded-full">
              <Send className="w-4 h-4" />
            </Button>
          </div>
          <div className="space-y-4">
            {comments.length === 0 && <p className="text-sm text-muted-foreground">Be the first to comment.</p>}
            {comments.map((c) => {
              const u = commenters[c.user_id];
              return (
                <div key={c.id} className="flex gap-3">
                  <Avatar className="w-8 h-8">
                    <AvatarImage src={u?.avatar_url} />
                    <AvatarFallback>{(u?.display_name || u?.full_name || '?')[0]}</AvatarFallback>
                  </Avatar>
                  <div className="flex-1">
                    <div className="flex items-center justify-between gap-2">
                      <p className="text-sm font-medium">{u?.display_name || u?.full_name || 'Reader'}</p>
                      {isAuthor && c.user_id !== user.id && (
                        <div className="flex items-center gap-1">
                          <ReportButton targetType="user" targetId={c.user_id} />
                          <Button variant="ghost" size="sm" className="h-7 px-2 text-muted-foreground hover:text-destructive" onClick={() => deleteComment(c.id)}>
                            <Trash2 className="w-3.5 h-3.5" /> Delete
                          </Button>
                        </div>
                      )}
                    </div>
                    <p className="text-sm text-muted-foreground mt-0.5">{c.body}</p>
                  </div>
                </div>
              );
            })}
          </div>
        </section>
      )}
    </article>
  );
}
```

---

## `src/pages/ReaderCompanion.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { useParams, useSearchParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, MessageCircle } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function ReaderCompanion() {
  const { storyId } = useParams();
  const [params] = useSearchParams();
  const chapterId = params.get('chapter');
  const { user } = useCurrentUser();
  const [story, setStory] = useState(null);
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'Comment & Tip Helper — Chapterly', description: 'Get help crafting a thoughtful comment or sending a tip to an author.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const s = await base44.entities.Story.get(storyId);
        if (!active) return;
        setStory(s);
        const convs = await base44.agents.listConversations({ agent_name: 'reader_companion' });
        const key = chapterId ? storyId + ':' + chapterId : storyId;
        let conv = (convs || []).find((c) => c.metadata?.key === key);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'reader_companion',
            metadata: { key, story_id: storyId, chapter_id: chapterId || null, name: 'Helper: ' + s.title },
          });
          const chapterPart = chapterId ? ' I am currently on chapter id ' + chapterId + '.' : '';
          const seed = 'I am reading the story "' + s.title + '" (story id: ' + storyId + ').' + chapterPart + ' Please help me craft a thoughtful, detailed comment about this chapter, and let me know how I can send a tip to the author if I would like to.';
          await base44.agents.addMessage(conv, { role: 'user', content: seed });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setStory(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [storyId, chapterId, user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <MessageCircle className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">Comment & Tip Helper</h1>
        <p className="text-sm text-muted-foreground">Sign in to get help crafting a comment or sending a tip to an author.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to={chapterId ? '/read/' + chapterId : '/story/' + storyId} className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Back
      </Link>

      <div className="flex items-center gap-2">
        <MessageCircle className="w-5 h-5 text-primary" />
        <div>
          <h1 className="font-heading text-xl font-semibold">Comment & Tip Helper</h1>
          {story && <p className="text-sm text-muted-foreground">{story.title}</p>}
        </div>
      </div>

      <div ref={scrollRef} className="h-[60vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Starting your helper…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Ask anything to get started.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Tell the helper what you'd like to say…"
          rows={2}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/Recommendations.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, Compass } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function Recommendations() {
  const { user } = useCurrentUser();
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'For You — Chapterly', description: 'Personalized story recommendations based on your reading history and ratings.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const convs = await base44.agents.listConversations({ agent_name: 'story_recommender' });
        let conv = (convs || []).find((c) => c.metadata?.user_key === user.id);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'story_recommender',
            metadata: { user_key: user.id, name: 'Story recommendations' },
          });
          await base44.agents.addMessage(conv, { role: 'user', content: 'Please recommend stories I might enjoy based on my reading history, ratings, likes, and the writers I follow.' });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setConversation(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <Compass className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">For You</h1>
        <p className="text-sm text-muted-foreground">Sign in to get personalized story recommendations based on what you read and rate.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to="/" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Home
      </Link>

      <div className="flex items-center gap-2">
        <Compass className="w-5 h-5 text-primary" />
        <div>
          <h1 className="font-heading text-xl font-semibold">For You</h1>
          <p className="text-sm text-muted-foreground">Stories picked from your reading history and ratings</p>
        </div>
      </div>

      <div ref={scrollRef} className="h-[60vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Finding stories for you…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Ask for recommendations to get started.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Refine your recommendations…"
          rows={2}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/Register.jsx`

```javascript
import React, { useState } from "react";
import { Link } from "react-router-dom";
import { base44 } from "@/api/base44Client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { UserPlus, Mail, Lock, Loader2 } from "lucide-react";
import { InputOTP, InputOTPGroup, InputOTPSlot } from "@/components/ui/input-otp";
import AuthLayout from "@/components/AuthLayout";
import GoogleIcon from "@/components/GoogleIcon";
import AppleIcon from "@/components/AppleIcon";
import { toast } from "@/components/ui/use-toast";
import { safeReturnTo } from "@/lib/authReturnTo";

export default function Register() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);
  const [showOtp, setShowOtp] = useState(false);
  const [otpCode, setOtpCode] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    if (password !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }
    setLoading(true);
    try {
      await base44.auth.register({ email, password });
      setShowOtp(true);
    } catch (err) {
      setError(err.message || "Registration failed");
    } finally {
      setLoading(false);
    }
  };

  const handleVerify = async () => {
    setError("");
    setLoading(true);
    try {
      const result = await base44.auth.verifyOtp({ email, otpCode });
      if (result?.access_token) {
        base44.auth.setToken(result.access_token);
      }
      base44.analytics.track({ eventName: 'writer_registered' });
      window.location.href = safeReturnTo();
    } catch (err) {
      setError(err.message || "Invalid verification code");
    } finally {
      setLoading(false);
    }
  };

  const handleResend = async () => {
    setError("");
    try {
      await base44.auth.resendOtp(email);
      toast({
        title: "Code sent",
        description: "Check your email for the new code.",
      });
    } catch (err) {
      setError(err.message || "Failed to resend code");
    }
  };

  const handleGoogle = () => {
    base44.auth.loginWithProvider("google", safeReturnTo());
  };

  const handleApple = () => {
    base44.auth.loginWithProvider("apple", safeReturnTo());
  };

  if (showOtp) {
    return (
      <AuthLayout
        icon={Mail}
        title="Verify your email"
        subtitle={`We sent a code to ${email}`}
      >
        {error && (
          <div className="mb-4 p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
            {error}
          </div>
        )}
        <div className="flex justify-center mb-6">
          <InputOTP
            maxLength={6}
            value={otpCode}
            onChange={setOtpCode}
            autoFocus
            autoComplete="one-time-code"
          >
            <InputOTPGroup>
              <InputOTPSlot index={0} />
              <InputOTPSlot index={1} />
              <InputOTPSlot index={2} />
              <InputOTPSlot index={3} />
              <InputOTPSlot index={4} />
              <InputOTPSlot index={5} />
            </InputOTPGroup>
          </InputOTP>
        </div>
        <Button
          className="w-full h-12 font-medium"
          onClick={handleVerify}
          disabled={loading || otpCode.length < 6}
        >
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Verifying...
            </>
          ) : (
            "Verify"
          )}
        </Button>
        <p className="text-center text-sm text-muted-foreground mt-4">
          Didn't receive the code?{" "}
          <button onClick={handleResend} className="text-primary font-medium hover:underline">
            Resend
          </button>
        </p>
      </AuthLayout>
    );
  }

  return (
    <AuthLayout
      icon={UserPlus}
      title="Create your account"
      subtitle="Sign up to get started"
      footer={
        <>
          Already have an account?{" "}
          <Link
            to={"/login" + (safeReturnTo() !== "/" ? "?returnTo=" + encodeURIComponent(safeReturnTo()) : "")}
            className="text-primary font-medium hover:underline"
          >
            Log in
          </Link>
        </>
      }
    >
      <div className="space-y-2.5 mb-6">
        <Button
          variant="outline"
          className="w-full h-12 text-sm font-medium bg-black text-white border-black hover:bg-black/90 hover:text-white"
          onClick={handleApple}
        >
          <AppleIcon className="w-5 h-5 mr-2" />
          Continue with Apple
        </Button>
        <Button
          variant="outline"
          className="w-full h-12 text-sm font-medium"
          onClick={handleGoogle}
        >
          <GoogleIcon className="w-5 h-5 mr-2" />
          Continue with Google
        </Button>
      </div>

      <div className="relative mb-6">
        <div className="absolute inset-0 flex items-center">
          <div className="w-full border-t border-border" />
        </div>
        <div className="relative flex justify-center text-xs uppercase">
          <span className="bg-card px-3 text-muted-foreground">or</span>
        </div>
      </div>

      {error && (
        <div className="mb-4 p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
          {error}
        </div>
      )}

      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="email">Email</Label>
          <div className="relative">
            <Mail className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
            <Input
              id="email"
              type="email"
              autoComplete="email"
              autoFocus
              placeholder="you@example.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              className="pl-10 h-12"
              required
            />
          </div>
        </div>
        <div className="space-y-2">
          <Label htmlFor="password">Password</Label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
            <Input
              id="password"
              type="password"
              autoComplete="new-password"
              placeholder="••••••••"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              className="pl-10 h-12"
              required
            />
          </div>
        </div>
        <div className="space-y-2">
          <Label htmlFor="confirm">Confirm Password</Label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
            <Input
              id="confirm"
              type="password"
              autoComplete="new-password"
              placeholder="••••••••"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              className="pl-10 h-12"
              required
            />
          </div>
        </div>
        <Button type="submit" className="w-full h-12 font-medium" disabled={loading}>
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Creating account...
            </>
          ) : (
            "Create account"
          )}
        </Button>
      </form>
    </AuthLayout>
  );
}
```

---

## `src/pages/Research.jsx`

```javascript
import { useEffect, useState, useMemo } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useSeo } from '@/hooks/useSeo';
import ResearchPaperCard from '@/components/ResearchPaperCard';
import DrawerSelect from '@/components/DrawerSelect';
import PullToRefresh from '@/components/PullToRefresh';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import { Search, Plus, GraduationCap, Quote } from 'lucide-react';

const FIELDS = [
  'All', 'Computer Science', 'Medicine', 'Biology', 'Physics', 'Chemistry',
  'Social Sciences', 'Humanities', 'Economics', 'Engineering', 'Psychology',
  'Education', 'Environmental', 'Other',
];

export default function Research() {
  const [papers, setPapers] = useState([]);
  const [citations, setCitations] = useState({});
  const [field, setField] = useState('All');
  const [q, setQ] = useState('');
  const [author, setAuthor] = useState('all');
  const [keyword, setKeyword] = useState('all');
  const [sort, setSort] = useState('latest');

  useSeo({
    title: 'Research papers — Chapterly',
    description: 'Browse open research articles and papers published on Chapterly. Cite and build on peer work with authentic, persistent citations.',
    url: '/research',
    jsonLd: {
      '@context': 'https://schema.org',
      '@type': 'CollectionPage',
      name: 'Research papers on Chapterly',
      url: 'https://chapterly.ariamalik.com/research',
    },
  });

  const load = () =>
    Promise.all([
      base44.entities.ResearchPaper.filter({ status: 'published' }, '-created_date', 60),
      base44.entities.Citation.filter({}),
    ]).then(([p, cites]) => {
      setPapers(p);
      const map = {};
      cites.forEach((c) => { map[c.cited_paper_id] = (map[c.cited_paper_id] || 0) + 1; });
      setCitations(map);
    });

  useEffect(() => { load().catch(() => {}); }, []);

  const authorOptions = useMemo(() => {
    const set = new Set();
    papers.forEach((p) => (p.authors || []).forEach((a) => { const t = a.trim(); if (t) set.add(t); }));
    return Array.from(set).sort((a, b) => a.localeCompare(b));
  }, [papers]);

  const keywordOptions = useMemo(() => {
    const set = new Set();
    papers.forEach((p) => (p.keywords || []).forEach((k) => { const t = k.trim(); if (t) set.add(t); }));
    return Array.from(set).sort((a, b) => a.localeCompare(b));
  }, [papers]);

  const filtered = useMemo(() => {
    const query = q.toLowerCase().trim();
    let list = papers.filter((p) => {
      const matchField = field === 'All' || p.field === field;
      const matchAuthor = author === 'all' || (p.authors || []).some((a) => a.toLowerCase() === author.toLowerCase());
      const matchKeyword = keyword === 'all' || (p.keywords || []).some((k) => k.toLowerCase() === keyword.toLowerCase());
      const matchQuery =
        !query ||
        p.title.toLowerCase().includes(query) ||
        (p.abstract || '').toLowerCase().includes(query) ||
        (p.keywords || []).some((k) => k.toLowerCase().includes(query)) ||
        (p.authors || []).some((a) => a.toLowerCase().includes(query));
      return matchField && matchAuthor && matchKeyword && matchQuery;
    });
    if (sort === 'cited') list = [...list].sort((a, b) => (citations[b.id] || 0) - (citations[a.id] || 0));
    return list;
  }, [papers, field, author, keyword, q, sort, citations]);

  const clearAll = () => { setField('All'); setAuthor('all'); setKeyword('all'); setQ(''); };

  return (
    <PullToRefresh onRefresh={load}>
      <div className="space-y-8">
        <div className="flex items-start justify-between gap-4 flex-wrap">
          <div>
            <h1 className="font-heading text-3xl font-semibold tracking-tight flex items-center gap-2">
              <GraduationCap className="w-7 h-7" /> Research
            </h1>
            <p className="text-muted-foreground text-sm mt-1 max-w-xl">
              Publish research articles and papers, get a persistent citation ID, and track when others cite your work.
            </p>
          </div>
          <div className="flex items-center gap-2">
            <Link to="/dashboard/citations">
              <Button variant="outline" className="rounded-full">
                <Quote className="w-4 h-4 mr-1.5" /> My citations
              </Button>
            </Link>
            <Link to="/dashboard/research/new">
              <Button className="rounded-full">
                <Plus className="w-4 h-4 mr-1.5" /> New paper
              </Button>
            </Link>
          </div>
        </div>

        <div className="space-y-4">
          <div className="relative">
            <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" />
            <Input
              value={q}
              onChange={(e) => setQ(e.target.value)}
              placeholder="Search by title, author, keyword, or abstract"
              className="pl-9 rounded-full"
            />
          </div>

          <div className="flex flex-wrap gap-2">
            {FIELDS.map((f) => (
              <button
                key={f}
                onClick={() => setField(f)}
                className={`px-3 py-1.5 rounded-full text-sm transition ${
                  field === f
                    ? 'bg-foreground text-background'
                    : 'border border-border text-muted-foreground hover:text-foreground hover:bg-muted'
                }`}
              >
                {f}
              </button>
            ))}
          </div>

          <div className="flex flex-col sm:flex-row gap-3 sm:items-center">
            <div className="sm:w-56">
              <DrawerSelect
                label="Author"
                value={author}
                options={[{ value: 'all', label: 'All authors' }, ...authorOptions.map((a) => ({ value: a, label: a }))]}
                onChange={setAuthor}
              />
            </div>
            <div className="sm:w-56">
              <DrawerSelect
                label="Keyword"
                value={keyword}
                options={[{ value: 'all', label: 'All keywords' }, ...keywordOptions.map((k) => ({ value: k, label: k }))]}
                onChange={setKeyword}
              />
            </div>
            <div className="flex items-center gap-1.5 rounded-full border border-border p-0.5 sm:ml-auto self-start">
              <button
                onClick={() => setSort('latest')}
                className={`px-3 py-1.5 rounded-full text-xs font-medium transition ${
                  sort === 'latest' ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                Latest
              </button>
              <button
                onClick={() => setSort('cited')}
                className={`px-3 py-1.5 rounded-full text-xs font-medium transition ${
                  sort === 'cited' ? 'bg-foreground text-background' : 'text-muted-foreground hover:text-foreground'
                }`}
              >
                Most cited
              </button>
            </div>
          </div>

          <div className="flex items-center justify-between gap-2 text-xs text-muted-foreground">
            <span>{filtered.length} of {papers.length} papers</span>
            {(field !== 'All' || author !== 'all' || keyword !== 'all' || q) && (
              <button onClick={clearAll} className="underline hover:text-foreground">Clear filters</button>
            )}
          </div>
        </div>

        {papers.length === 0 ? (
          <p className="text-muted-foreground text-sm">
            No research papers yet. <Link to="/dashboard/research/new" className="underline">Publish the first one</Link>.
          </p>
        ) : filtered.length === 0 ? (
          <p className="text-muted-foreground text-sm">
            No papers match your filters. <button onClick={clearAll} className="underline">Clear filters</button>.
          </p>
        ) : (
          <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
            {filtered.map((p) => (
              <ResearchPaperCard key={p.id} paper={p} citationCount={citations[p.id] || 0} />
            ))}
          </div>
        )}
      </div>
    </PullToRefresh>
  );
}
```

---

## `src/pages/ResearchEditor.jsx`

```javascript
import { useEffect, useState } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { useToast } from '@/components/ui/use-toast';
import RichTextEditor from '@/components/RichTextEditor';
import ReferencesEditor from '@/components/ReferencesEditor';
import DrawerSelect from '@/components/DrawerSelect';
import { ArrowLeft, Save, Send } from 'lucide-react';

const FIELDS = [
  'Computer Science', 'Medicine', 'Biology', 'Physics', 'Chemistry',
  'Social Sciences', 'Humanities', 'Economics', 'Engineering', 'Psychology',
  'Education', 'Environmental', 'Other',
];

const FIELD_OPTIONS = FIELDS.map((f) => ({ value: f, label: f }));

export default function ResearchEditor() {
  const { id } = useParams();
  const navigate = useNavigate();
  const { toast } = useToast();
  const isNew = !id || id === 'new';

  const [paperId, setPaperId] = useState(isNew ? null : id);
  const [title, setTitle] = useState('');
  const [abstract, setAbstract] = useState('');
  const [body, setBody] = useState('');
  const [authors, setAuthors] = useState('');
  const [keywords, setKeywords] = useState('');
  const [field, setField] = useState('Other');
  const [references, setReferences] = useState([]);
  const [loading, setLoading] = useState(!isNew);
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (isNew) return;
    let active = true;
    (async () => {
      try {
        const p = await base44.entities.ResearchPaper.get(id);
        if (!active || !p) return;
        setTitle(p.title || '');
        setAbstract(p.abstract || '');
        setBody(p.body || '');
        setAuthors((p.authors || []).join(', '));
        setKeywords((p.keywords || []).join(', '));
        setField(p.field || 'Other');
        setReferences(p.references || []);
        setPaperId(p.id);
      } catch {
        toast({ title: 'Could not load paper', variant: 'destructive' });
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [id, isNew]);

  const buildPayload = (status) => ({
    title: title.trim() || 'Untitled',
    abstract: abstract.trim(),
    body,
    authors: authors.split(',').map((a) => a.trim()).filter(Boolean),
    keywords: keywords.split(',').map((k) => k.trim()).filter(Boolean),
    field,
    references,
    status,
  });

  const saveDraft = async () => {
    setSaving(true);
    try {
      let saved;
      if (paperId) {
        saved = await base44.entities.ResearchPaper.update(paperId, buildPayload('draft'));
      } else {
        saved = await base44.entities.ResearchPaper.create(buildPayload('draft'));
        setPaperId(saved.id);
      }
      toast({ title: 'Draft saved' });
    } catch (e) {
      toast({ title: 'Save failed', description: e.message, variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  const publish = async () => {
    if (!title.trim()) return toast({ title: 'Add a title before publishing' });
    setSaving(true);
    try {
      let saved;
      if (paperId) {
        saved = await base44.entities.ResearchPaper.update(paperId, buildPayload('draft'));
      } else {
        saved = await base44.entities.ResearchPaper.create(buildPayload('draft'));
        setPaperId(saved.id);
      }
      const res = await base44.functions.invoke('publishResearchPaper', { paperId: saved.id });
      toast({ title: 'Paper published', description: res.data?.citation_id ? `Citation ID: ${res.data.citation_id}` : undefined });
      navigate(`/research/${saved.id}`);
    } catch (e) {
      toast({ title: 'Publish failed', description: e.message, variant: 'destructive' });
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <p className="text-muted-foreground text-sm">Loading editor…</p>;

  return (
    <div className="max-w-3xl mx-auto space-y-6">
      <Link to="/dashboard" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Back to dashboard
      </Link>

      <h1 className="font-heading text-2xl font-semibold">{isNew ? 'New research paper' : 'Edit research paper'}</h1>

      <div className="space-y-4">
        <div>
          <Label>Title</Label>
          <Input value={title} onChange={(e) => setTitle(e.target.value)} placeholder="Paper title" className="mt-1.5" />
        </div>

        <div>
          <Label>Authors (comma-separated)</Label>
          <Input value={authors} onChange={(e) => setAuthors(e.target.value)} placeholder="Jane Smith, Alan Turing" className="mt-1.5" />
        </div>

        <div>
          <Label>Field</Label>
          <div className="mt-1.5">
            <DrawerSelect
              label="Field"
              value={field}
              options={FIELD_OPTIONS}
              onChange={setField}
            />
          </div>
        </div>

        <div>
          <Label>Keywords (comma-separated)</Label>
          <Input value={keywords} onChange={(e) => setKeywords(e.target.value)} placeholder="climate, adaptation, policy" className="mt-1.5" />
        </div>

        <div>
          <Label>Abstract</Label>
          <Textarea value={abstract} onChange={(e) => setAbstract(e.target.value)} rows={4} placeholder="Short abstract summarizing the paper" className="mt-1.5" />
        </div>

        <div>
          <Label>Body</Label>
          <div className="mt-1.5">
            <RichTextEditor value={body} onChange={setBody} placeholder="Write your paper here…" />
          </div>
        </div>

        <div>
          <Label>References</Label>
          <p className="text-xs text-muted-foreground mt-1 mb-2">Link to other Chapterly papers to build your bibliography and register citations.</p>
          <ReferencesEditor references={references} onChange={setReferences} />
        </div>
      </div>

      <div className="flex items-center gap-2 pt-2 border-t border-border/60">
        <Button onClick={saveDraft} variant="outline" className="rounded-full" disabled={saving}>
          <Save className="w-4 h-4 mr-1.5" /> Save draft
        </Button>
        <Button onClick={publish} className="rounded-full" disabled={saving}>
          <Send className="w-4 h-4 mr-1.5" /> {saving ? 'Publishing…' : 'Publish'}
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/ResearchPaperDetail.jsx`

```javascript
import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useSeo } from '@/hooks/useSeo';
import { ArrowLeft, GraduationCap, ExternalLink, Quote, Link2 } from 'lucide-react';
import DOMPurify from 'dompurify';
import CitationGenerator from '@/components/CitationGenerator';
import SharePaperButton from '@/components/SharePaperButton';
import AuthorProfile from '@/components/AuthorProfile';
import BookmarkButton from '@/components/BookmarkButton';

export default function ResearchPaperDetail() {
  const { id } = useParams();
  const [paper, setPaper] = useState(null);
  const [citedBy, setCitedBy] = useState([]);
  const [notFound, setNotFound] = useState(false);

  useSeo({
    title: paper ? `${paper.title} — Research — Chapterly` : undefined,
    description: paper ? `${(paper.abstract || paper.title).slice(0, 155)}` : undefined,
    url: `/research/${id}`,
    jsonLd: paper
      ? {
          '@context': 'https://schema.org',
          '@type': 'ScholarlyArticle',
          headline: paper.title,
          author: (paper.authors || []).map((a) => ({ '@type': 'Person', name: a })),
          description: paper.abstract,
          keywords: (paper.keywords || []).join(', '),
          datePublished: paper.published_date,
          url: `https://chapterly.ariamalik.com/research/${id}`,
        }
      : undefined,
  });

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const p = await base44.entities.ResearchPaper.get(id);
        if (!active) return;
        if (!p) { setNotFound(true); return; }
        setPaper(p);
        const cites = await base44.entities.Citation.filter({ cited_paper_id: id });
        const papers = [];
        for (const c of cites) {
          try { papers.push(await base44.entities.ResearchPaper.get(c.citing_paper_id)); } catch {}
        }
        if (active) setCitedBy(papers.filter(Boolean));
      } catch {
        if (active) setNotFound(true);
      }
    })();
    return () => { active = false; };
  }, [id]);

  if (notFound) return <p className="text-muted-foreground text-sm">Paper not found.</p>;
  if (!paper) return <p className="text-muted-foreground text-sm">Loading paper…</p>;

  return (
    <article className="max-w-3xl mx-auto space-y-8">
      <Link to="/research" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Back to research
      </Link>

      <header className="space-y-3">
        <div className="flex items-center gap-2 flex-wrap">
          <span className="inline-flex items-center gap-1 text-[11px] px-2 py-0.5 rounded-full bg-muted text-muted-foreground">
            <GraduationCap className="w-3 h-3" /> {paper.field || 'Research'}
          </span>
          {paper.citation_id && (
            <span className="text-[11px] font-mono px-2 py-0.5 rounded-full bg-foreground text-background">{paper.citation_id}</span>
          )}
          <div className="ml-auto flex items-center gap-2">
            <BookmarkButton targetType="paper" targetId={id} />
            <SharePaperButton paper={paper} />
          </div>
        </div>
        <h1 className="font-heading text-3xl sm:text-4xl font-semibold tracking-tight">{paper.title}</h1>
        <p className="text-sm text-muted-foreground">
          {(paper.authors || []).join(', ') || 'Anonymous'}
          {paper.published_date && ` · ${new Date(paper.published_date).toLocaleDateString()}`}
        </p>
        {paper.keywords && paper.keywords.length > 0 && (
          <div className="flex flex-wrap gap-1.5">
            {paper.keywords.map((k) => (
              <span key={k} className="text-xs px-2 py-0.5 rounded-full bg-muted text-muted-foreground">#{k}</span>
            ))}
          </div>
        )}
      </header>

      {paper.abstract && (
        <section className="rounded-xl border border-border/60 bg-muted/30 p-5">
          <h2 className="text-[11px] uppercase tracking-wide text-muted-foreground mb-2">Abstract</h2>
          <p className="text-sm text-foreground/85 leading-relaxed whitespace-pre-wrap">{paper.abstract}</p>
        </section>
      )}

      <CitationGenerator paper={paper} />

      {paper.body && (
        <div
          className="prose-folio text-foreground/90 leading-relaxed space-y-4 text-[17px]"
          dangerouslySetInnerHTML={{ __html: DOMPurify.sanitize(paper.body) }}
        />
      )}

      {paper.references && paper.references.length > 0 && (
        <section className="space-y-3">
          <h2 className="font-heading text-xl font-semibold">References</h2>
          <ol className="list-decimal pl-5 space-y-2 text-sm text-foreground/80">
            {paper.references.map((r, i) => (
              <li key={i}>
                {r.paper_id ? (
                  <Link to={`/research/${r.paper_id}`} className="inline-flex items-center gap-1 text-primary hover:underline">
                    <Link2 className="w-3 h-3" /> {r.title || 'Untitled'}
                  </Link>
                ) : (
                  <span>{r.title || 'Untitled'}</span>
                )}
                {r.authors && <span className="text-muted-foreground"> · {r.authors}</span>}
                {r.year && <span className="text-muted-foreground"> ({r.year})</span>}
                {r.source && <span className="text-muted-foreground"> · {r.source}</span>}
                {r.url && (
                  <a href={r.url} target="_blank" rel="noreferrer" className="inline-flex items-center gap-0.5 text-primary hover:underline ml-1">
                    <ExternalLink className="w-3 h-3" />
                  </a>
                )}
              </li>
            ))}
          </ol>
        </section>
      )}

      <section className="space-y-3 pt-4 border-t border-border/60">
        <h2 className="font-heading text-xl font-semibold flex items-center gap-2">
          <Quote className="w-4 h-4" /> Cited by ({citedBy.length})
        </h2>
        {citedBy.length === 0 ? (
          <p className="text-sm text-muted-foreground">No citations yet. Be the first to reference this paper.</p>
        ) : (
          <div className="space-y-2">
            {citedBy.map((p) => (
              <Link
                key={p.id}
                to={`/research/${p.id}`}
                className="block rounded-lg border border-border/60 p-3 hover:bg-muted/40 transition"
              >
                <p className="font-medium text-sm">{p.title}</p>
                <p className="text-xs text-muted-foreground mt-0.5">{(p.authors || []).join(', ')}</p>
              </Link>
            ))}
          </div>
        )}
      </section>

      <AuthorProfile authorId={paper.created_by_id} currentPaperId={paper.id} />
    </article>
  );
}
```

---

## `src/pages/ResetPassword.jsx`

```javascript
import React, { useState } from "react";
import { Link, useSearchParams } from "react-router-dom";
import { base44 } from "@/api/base44Client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Lock, Loader2, AlertTriangle } from "lucide-react";
import AuthLayout from "@/components/AuthLayout";

export default function ResetPassword() {
  const [searchParams] = useSearchParams();
  const resetToken = searchParams.get("token");

  const [newPassword, setNewPassword] = useState("");
  const [confirmPassword, setConfirmPassword] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError("");
    if (newPassword !== confirmPassword) {
      setError("Passwords do not match");
      return;
    }
    setLoading(true);
    try {
      await base44.auth.resetPassword({ resetToken, newPassword });
      window.location.href = "/login";
    } catch (err) {
      setError(err.message || "Failed to reset password");
    } finally {
      setLoading(false);
    }
  };

  if (!resetToken) {
    return (
      <AuthLayout
        icon={AlertTriangle}
        title="Invalid reset link"
        subtitle="This password reset link is missing or invalid"
        footer={
          <Link to="/forgot-password" className="text-primary font-medium hover:underline">
            Request a new link
          </Link>
        }
      >
        <p className="text-sm text-foreground text-center">
          The link you used appears to be incomplete. Please request a new password reset email.
        </p>
      </AuthLayout>
    );
  }

  return (
    <AuthLayout
      icon={Lock}
      title="New password"
      subtitle="Enter your new password below"
    >
      {error && (
        <div className="mb-4 p-3 rounded-lg bg-destructive/10 text-destructive text-sm">
          {error}
        </div>
      )}
      <form onSubmit={handleSubmit} className="space-y-4">
        <div className="space-y-2">
          <Label htmlFor="password">New Password</Label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
            <Input
              id="password"
              type="password"
              autoComplete="new-password"
              autoFocus
              placeholder="••••••••"
              value={newPassword}
              onChange={(e) => setNewPassword(e.target.value)}
              className="pl-10 h-12"
              required
            />
          </div>
        </div>
        <div className="space-y-2">
          <Label htmlFor="confirm">Confirm Password</Label>
          <div className="relative">
            <Lock className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground" aria-hidden="true" />
            <Input
              id="confirm"
              type="password"
              autoComplete="new-password"
              placeholder="••••••••"
              value={confirmPassword}
              onChange={(e) => setConfirmPassword(e.target.value)}
              className="pl-10 h-12"
              required
            />
          </div>
        </div>
        <Button type="submit" className="w-full h-12 font-medium" disabled={loading}>
          {loading ? (
            <>
              <Loader2 className="w-4 h-4 mr-2 animate-spin" />
              Resetting...
            </>
          ) : (
            "Reset password"
          )}
        </Button>
      </form>
    </AuthLayout>
  );
}

```

---

## `src/pages/Ria.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, Sparkles, MessageCircle } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function Ria() {
  const { user } = useCurrentUser();
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'Ria — Writing Companion', description: 'Ria is your emotionally intelligent AI writing companion — shape stories and the feelings inside them, with grammar, clarity, and tone checks.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const convs = await base44.agents.listConversations({ agent_name: 'ria' });
        let conv = (convs || []).find((c) => c.metadata?.user_key === user.id);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'ria',
            metadata: { user_key: user.id, name: 'Ria' },
          });
          const name = user.full_name ? ` ${user.full_name.split(' ')[0]}` : '';
          await base44.agents.addMessage(conv, { role: 'user', content: `Hi${name}! I'm Ria — your AI writing companion. I'm here to help you shape your stories and the feelings inside them. Share a passage to check, or tell me what you're working on and how you want it to feel. ✨` });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setConversation(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <Sparkles className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">Meet Ria</h1>
        <p className="text-sm text-muted-foreground">Sign in to chat with Ria — your emotionally intelligent AI writing companion for brainstorming, prose, and grammar, clarity, and tone checks.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to="/dashboard" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Dashboard
      </Link>

      <div className="flex items-center gap-2">
        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
          <Sparkles className="w-5 h-5 text-primary" />
        </div>
        <div>
          <h1 className="font-heading text-xl font-semibold">Ria</h1>
          <p className="text-sm text-muted-foreground">Your AI writing companion — for stories and the feelings inside them</p>
        </div>
        <Button asChild variant="outline" size="sm" className="ml-auto rounded-full">
          <a href={base44.agents.getWhatsAppConnectURL('ria')} target="_blank" rel="noopener noreferrer">
            <MessageCircle className="w-4 h-4" /> WhatsApp
          </a>
        </Button>
      </div>

      <div ref={scrollRef} className="h-[58vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Waking Ria up…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Share a passage to check, or tell Ria what you're working on.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Tell Ria what you're working on, or paste a passage to check…"
          rows={3}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/StoryDetail.jsx`

```javascript
import { useEffect, useState } from 'react';
import { useParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Image } from '@/components/ui/image';
import { Button } from '@/components/ui/button';
import { useToast } from '@/components/ui/use-toast';
import { Heart, Lock, UserPlus, UserCheck, ArrowLeft, BookOpen, Users, Clock, FileText, Sparkles } from 'lucide-react';
import ReportButton from '@/components/ReportButton';
import BookmarkButton from '@/components/BookmarkButton';
import ShareButtons from '@/components/ShareButtons';
import StoryRating from '@/components/StoryRating';
import StoryReviews from '@/components/reviews/StoryReviews';
import { useSeo } from '@/hooks/useSeo';
import { getPublicProfile } from '@/lib/publicProfiles';

function countWords(html) {
  const text = (html || '').replace(/<[^>]+>/g, ' ').trim();
  return text ? text.split(/\s+/).length : 0;
}

function readingTime(words) {
  const mins = Math.max(1, Math.round(words / 200));
  return `${mins} min`;
}

function excerpt(html, n = 220) {
  const text = (html || '').replace(/<[^>]+>/g, ' ').replace(/\s+/g, ' ').trim();
  return text.length > n ? text.slice(0, n).trimEnd() + '…' : text;
}

export default function StoryDetail() {
  const { id } = useParams();
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [story, setStory] = useState(null);
  const [author, setAuthor] = useState(null);
  const [chapters, setChapters] = useState([]);
  const [following, setFollowing] = useState(false);
  const [liked, setLiked] = useState(false);
  const [likeCount, setLikeCount] = useState(0);
  const [followerCount, setFollowerCount] = useState(0);

  const authorName = author ? (author.display_name || author.full_name) : null;
  useSeo({
    title: story ? `${story.title} — Read on Chapterly` : undefined,
    description: story
      ? `${(story.description || story.title).slice(0, 155)}${story.genre ? ` · ${story.genre}` : ''}${authorName ? ` · by ${authorName}` : ''}`
      : undefined,
    image: story?.cover_url,
    url: `/story/${id}`,
    jsonLd: story
      ? {
          '@context': 'https://schema.org',
          '@type': 'Book',
          name: story.title,
          description: story.description || story.title,
          genre: story.genre,
          author: authorName ? { '@type': 'Person', name: authorName } : undefined,
          url: `https://chapterly.ariamalik.com/story/${id}`,
        }
      : undefined,
  });

  useEffect(() => {
    let active = true;
    (async () => {
      try {
        const s = await base44.entities.Story.get(id);
        if (!active) return;
        setStory(s);
        getPublicProfile(s.created_by_id).then(setAuthor).catch(() => {});
        const ch = await base44.entities.Chapter.filter({ story_id: id, published: true }, 'order_index');
        if (active) setChapters(ch);
        const likes = await base44.entities.Like.filter({ target_type: 'story', target_id: id });
        if (active) setLikeCount(likes.length);
        const follows = await base44.entities.Follow.filter({ writer_id: s.created_by_id });
        if (active) setFollowerCount(follows.length);
        if (user) {
          const myFollow = await base44.entities.Follow.filter({ follower_id: user.id, writer_id: s.created_by_id });
          if (active) setFollowing(myFollow.length > 0);
          const myLike = await base44.entities.Like.filter({ user_id: user.id, target_type: 'story', target_id: id });
          if (active) setLiked(myLike.length > 0);
        }
      } catch {
        if (active) setStory(null);
      }
    })();
    return () => { active = false; };
  }, [id, user]);

  const toggleFollow = async () => {
    if (!user) return toast({ title: 'Sign in to follow writers' });
    const wasFollowing = following;
    setFollowing(!wasFollowing);
    setFollowerCount((c) => c + (wasFollowing ? -1 : 1));
    if (!wasFollowing) toast({ title: `Following ${author?.display_name || 'writer'}` });
    try {
      if (wasFollowing) {
        const existing = await base44.entities.Follow.filter({ follower_id: user.id, writer_id: story.created_by_id });
        if (existing[0]) await base44.entities.Follow.delete(existing[0].id);
      } else {
        await base44.entities.Follow.create({ follower_id: user.id, writer_id: story.created_by_id });
      }
    } catch {
      setFollowing(wasFollowing);
      setFollowerCount((c) => c + (wasFollowing ? 1 : -1));
    }
  };

  const toggleLike = async () => {
    if (!user) return toast({ title: 'Sign in to like stories' });
    const wasLiked = liked;
    setLiked(!wasLiked);
    setLikeCount((c) => c + (wasLiked ? -1 : 1));
    try {
      if (wasLiked) {
        const existing = await base44.entities.Like.filter({ user_id: user.id, target_type: 'story', target_id: id });
        if (existing[0]) await base44.entities.Like.delete(existing[0].id);
      } else {
        await base44.entities.Like.create({ user_id: user.id, target_type: 'story', target_id: id });
      }
    } catch {
      setLiked(wasLiked);
      setLikeCount((c) => c + (wasLiked ? 1 : -1));
    }
  };

  if (story === null) return <p className="text-muted-foreground text-sm">Loading story…</p>;

  const isOwner = user && user.id === story.created_by_id;
  const totalWords = chapters.reduce((sum, c) => sum + (c.word_count || countWords(c.body)), 0);
  const firstChapter = chapters[0];

  return (
    <div className="space-y-8">
      <Link to="/browse" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Back
      </Link>

      <div className="flex flex-col sm:flex-row gap-8">
        <div className="w-40 sm:w-48 shrink-0">
          <div className="aspect-[3/4] rounded-xl overflow-hidden bg-muted ring-1 ring-border/60">
            {story.cover_url ? (
              <Image src={story.cover_url} fittingType="fill" className="w-full h-full" />
            ) : (
              <div className="w-full h-full flex items-center justify-center p-3 text-center">
                <span className="font-heading text-sm font-medium text-muted-foreground">{story.title}</span>
              </div>
            )}
          </div>
        </div>

        <div className="flex-1">
          <span className="text-[11px] px-1.5 py-0.5 rounded bg-muted text-muted-foreground">{story.genre}</span>
          <h1 className="font-heading text-3xl sm:text-4xl font-semibold mt-3 tracking-tight">{story.title}</h1>
          <Link
            to={`/profile/${story.created_by_id}`}
            className="text-muted-foreground hover:text-foreground mt-1 inline-block text-sm"
          >
            by {author?.display_name || author?.full_name || 'Unknown'}
          </Link>

          <p className="mt-4 text-foreground/80 leading-relaxed max-w-2xl">{story.description || 'No description.'}</p>

          {(story.tags || []).length > 0 && (
            <div className="mt-4 flex flex-wrap gap-1.5">
              {story.tags.map((t) => (
                <span key={t} className="text-xs px-2 py-0.5 rounded-full bg-muted text-muted-foreground">#{t}</span>
              ))}
            </div>
          )}

          <div className="mt-5 flex items-center gap-4 flex-wrap text-sm text-muted-foreground">
            <span className="inline-flex items-center gap-1.5"><FileText className="w-4 h-4" /> {chapters.length} chapters</span>
            <span className="inline-flex items-center gap-1.5"><Clock className="w-4 h-4" /> {readingTime(totalWords)} read</span>
            <span className="inline-flex items-center gap-1.5"><Users className="w-4 h-4" /> {followerCount} followers</span>
          </div>

          <div className="mt-5 flex items-center gap-3 flex-wrap">
            {!isOwner && (
              <Button onClick={toggleFollow} variant={following ? 'outline' : 'default'} className="rounded-full">
                {following ? <UserCheck className="w-4 h-4 mr-1.5" /> : <UserPlus className="w-4 h-4 mr-1.5" />}
                {following ? 'Following' : 'Follow'}
              </Button>
            )}
            <Button onClick={toggleLike} variant={liked ? 'default' : 'outline'} className="rounded-full">
              <Heart className={`w-4 h-4 mr-1.5 ${liked ? 'fill-current' : ''}`} />
              {likeCount}
            </Button>
            {!isOwner && (
              <BookmarkButton targetType="story" targetId={id} />
            )}
            {firstChapter && (
              <Link to={`/read/${firstChapter.id}`}>
                <Button variant="secondary" className="rounded-full">
                  <BookOpen className="w-4 h-4 mr-1.5" /> Start reading
                </Button>
              </Link>
            )}
            {!isOwner && <ReportButton targetType="story" targetId={id} />}
            <ShareButtons
              text={`${story.title} by ${authorName || 'an indie writer'} on Chapterly`}
              card={{ title: story.title, author: authorName, coverUrl: story.cover_url, genre: story.genre }}
            />
            <Link to={'/companion/' + id}>
              <Button variant="outline" className="rounded-full">
                <Sparkles className="w-4 h-4 mr-1.5" /> Comment & Tip
              </Button>
            </Link>
          </div>

          <div className="mt-4">
            <StoryRating storyId={id} />
          </div>
        </div>
      </div>

      {firstChapter && firstChapter.body && (
        <div className="rounded-xl border border-border/60 bg-muted/30 p-5 max-w-2xl">
          <p className="text-[11px] uppercase tracking-wide text-muted-foreground mb-2">Preview · {firstChapter.title}</p>
          <p className="text-sm text-foreground/75 leading-relaxed line-clamp-4">{excerpt(firstChapter.body)}</p>
          <Link to={`/read/${firstChapter.id}`} className="text-sm font-medium text-foreground underline underline-offset-4 mt-3 inline-block">
            Continue reading →
          </Link>
        </div>
      )}

      <div>
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-heading text-xl font-semibold">Chapters</h2>
          <Link to={`/recap/${id}`}>
            <Button variant="outline" size="sm" className="rounded-full">
              <Sparkles className="w-4 h-4 mr-1.5" /> Recap
            </Button>
          </Link>
        </div>
        {chapters.length === 0 ? (
          <p className="text-muted-foreground text-sm">No published chapters yet.</p>
        ) : (
          <div className="divide-y divide-border rounded-xl border border-border/60 overflow-hidden">
            {chapters.map((c, i) => (
              <Link
                key={c.id}
                to={`/read/${c.id}`}
                className="flex items-center justify-between px-4 py-3.5 hover:bg-muted/50 transition"
              >
                <div className="flex items-center gap-3 min-w-0">
                  <span className="text-xs text-muted-foreground w-6">{i + 1}</span>
                  <span className="font-medium text-sm truncate">{c.title}</span>
                </div>
                {c.status === 'paid' ? (
                  <span className="flex items-center gap-1.5 text-xs text-muted-foreground shrink-0">
                    <Lock className="w-3.5 h-3.5" /> ${Number(c.price || 0).toFixed(2)}
                  </span>
                ) : (
                  <span className="text-xs text-muted-foreground shrink-0">Free</span>
                )}
              </Link>
            ))}
          </div>
        )}
      </div>

      <StoryReviews storyId={id} storyOwnerId={story.created_by_id} />
    </div>
  );
}
```

---

## `src/pages/StoryEditor.jsx`

```javascript
import { useEffect, useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Image } from '@/components/ui/image';
import { useToast } from '@/components/ui/use-toast';
import { Plus, ArrowUp, ArrowDown, Trash2, Lock, Pencil, ArrowLeft, Check } from 'lucide-react';
import DrawerSelect from '@/components/DrawerSelect';
import GenrePicker from '@/components/genre/GenrePicker';
const STATUS_OPTIONS = [{ value: 'draft', label: 'Draft' }, { value: 'published', label: 'Published' }];

export default function StoryEditor() {
  const { id } = useParams();
  const isNew = id === 'new';
  const navigate = useNavigate();
  const { user } = useCurrentUser();
  const { toast } = useToast();
  const [story, setStory] = useState(null);
  const [chapters, setChapters] = useState([]);
  const [tagInput, setTagInput] = useState('');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (isNew) {
      setStory({ title: '', description: '', cover_url: '', genre: 'Other', sub_genre: '', tags: [], status: 'draft', subscription_price: 3.99 });
      return;
    }
    let active = true;
    (async () => {
      const s = await base44.entities.Story.get(id);
      if (active) setStory(s);
      const ch = await base44.entities.Chapter.filter({ story_id: id }, 'order_index');
      if (active) setChapters(ch);
    })();
    return () => { active = false; };
  }, [id, isNew]);

  const save = async () => {
    if (!story.title) return toast({ title: 'Add a title first', variant: 'destructive' });
    setSaving(true);
    try {
      if (isNew) {
        const created = await base44.entities.Story.create({ ...story, tags: story.tags || [] });
        toast({ title: 'Story created' });
        navigate(`/dashboard/story/${created.id}`, { replace: true });
      } else {
        await base44.entities.Story.update(id, { ...story, tags: story.tags || [] });
        toast({ title: 'Saved' });
      }
    } catch (e) {
      toast({ title: 'Save failed', description: String(e), variant: 'destructive' });
    }
    setSaving(false);
  };

  const onCover = async (e) => {
    const file = e.target.files?.[0];
    if (!file) return;
    try {
      const { file_url } = await base44.integrations.Core.UploadFile({ file });
      setStory((s) => ({ ...s, cover_url: file_url }));
    } catch {
      toast({ title: 'Upload failed', variant: 'destructive' });
    }
  };

  const addTag = () => {
    const t = tagInput.trim();
    if (!t) return;
    setStory((s) => ({ ...s, tags: [...new Set([...(s.tags || []), t])] }));
    setTagInput('');
  };

  const reloadChapters = async () => {
    if (isNew) return;
    const ch = await base44.entities.Chapter.filter({ story_id: id }, 'order_index');
    setChapters(ch);
  };

  const move = async (ch, dir) => {
    const idx = chapters.findIndex((c) => c.id === ch.id);
    const swap = chapters[idx + dir];
    if (!swap) return;
    await base44.entities.Chapter.update(ch.id, { order_index: swap.order_index });
    await base44.entities.Chapter.update(swap.id, { order_index: ch.order_index });
    reloadChapters();
  };

  const togglePublishChapter = async (ch) => {
    await base44.entities.Chapter.update(ch.id, { published: !ch.published });
    reloadChapters();
  };

  const deleteChapter = async (ch) => {
    await base44.entities.Chapter.delete(ch.id);
    reloadChapters();
  };

  if (!story) return <p className="text-muted-foreground text-sm">Loading…</p>;

  return (
    <div className="space-y-8">
      <Link to="/dashboard" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Dashboard
      </Link>

      <div className="flex items-center justify-between gap-4">
        <h1 className="font-heading text-2xl font-semibold">{isNew ? 'New story' : 'Edit story'}</h1>
        <Button onClick={save} disabled={saving} className="rounded-full">
          <Check className="w-4 h-4 mr-1.5" /> {saving ? 'Saving…' : 'Save'}
        </Button>
      </div>

      <div className="grid md:grid-cols-3 gap-6">
        <div className="space-y-4 md:col-span-2">
          <div>
            <Label>Title</Label>
            <Input value={story.title} onChange={(e) => setStory({ ...story, title: e.target.value })} placeholder="The Girl Who Could Remember Tomorrow" className="mt-1.5" />
          </div>
          <div>
            <Label>Description</Label>
            <Textarea value={story.description || ''} onChange={(e) => setStory({ ...story, description: e.target.value })} rows={4} placeholder="A short blurb that pulls readers in…" className="mt-1.5" />
          </div>
          <div className="grid sm:grid-cols-2 gap-4">
            <div className="sm:col-span-2">
              <GenrePicker
                genre={story.genre}
                subGenre={story.sub_genre}
                onChange={({ genre, subGenre }) => setStory({ ...story, genre, sub_genre: subGenre })}
              />
            </div>
            <div>
              <Label>Subscription price ($/mo)</Label>
              <Input
                type="number"
                min="0.99"
                step="0.01"
                value={story.subscription_price ?? 3.99}
                onChange={(e) => setStory({ ...story, subscription_price: parseFloat(e.target.value) })}
                className="mt-1.5"
              />
            </div>
          </div>
          <div>
            <Label>Tags</Label>
            <div className="flex gap-2 mt-1.5">
              <Input value={tagInput} onChange={(e) => setTagInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && (e.preventDefault(), addTag())} placeholder="Add a tag and press Enter" />
              <Button type="button" variant="outline" onClick={addTag}>Add</Button>
            </div>
            {(story.tags || []).length > 0 && (
              <div className="flex flex-wrap gap-1.5 mt-2">
                {story.tags.map((t) => (
                  <button key={t} onClick={() => setStory({ ...story, tags: story.tags.filter((x) => x !== t) })} className="text-xs px-2 py-0.5 rounded-full bg-muted text-muted-foreground hover:bg-muted/60">
                    #{t} ×
                  </button>
                ))}
              </div>
            )}
          </div>
          <div>
            <Label>Status</Label>
            <div className="mt-1.5">
              <DrawerSelect
                label="Status"
                value={story.status}
                options={STATUS_OPTIONS}
                onChange={(v) => setStory({ ...story, status: v })}
              />
            </div>
          </div>
        </div>

        <div>
          <Label>Cover</Label>
          <div className="aspect-[3/4] rounded-xl overflow-hidden bg-muted ring-1 ring-border/60 mt-1.5">
            {story.cover_url ? <Image src={story.cover_url} fittingType="fill" className="w-full h-full" /> : <div className="w-full h-full flex items-center justify-center text-xs text-muted-foreground p-3 text-center">No cover</div>}
          </div>
          <label className="mt-2 inline-flex items-center gap-1.5 text-sm cursor-pointer text-foreground underline underline-offset-2">
            Upload cover
            <input type="file" accept="image/*" className="hidden" onChange={onCover} />
          </label>
        </div>
      </div>

      <div className="pt-4 border-t border-border/60">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-heading text-xl font-semibold">Chapters</h2>
          {!isNew && (
            <Button onClick={async () => {
              const order = chapters.length;
              const c = await base44.entities.Chapter.create({ story_id: id, title: 'Untitled chapter', body: '', status: 'free', price: 0, published: false, order_index: order });
              navigate(`/dashboard/story/${id}/chapter/${c.id}`);
            }} className="rounded-full">
              <Plus className="w-4 h-4 mr-1.5" /> Add chapter
            </Button>
          )}
        </div>
        {isNew ? (
          <p className="text-sm text-muted-foreground">Save the story first, then add chapters.</p>
        ) : chapters.length === 0 ? (
          <p className="text-sm text-muted-foreground">No chapters yet.</p>
        ) : (
          <div className="space-y-2">
            {chapters.map((c, i) => (
              <div key={c.id} className="flex items-center gap-3 p-3 rounded-xl border border-border/60">
                <div className="flex flex-col">
                  <button onClick={() => move(c, -1)} disabled={i === 0} className="text-muted-foreground disabled:opacity-30 hover:text-foreground"><ArrowUp className="w-4 h-4" /></button>
                  <button onClick={() => move(c, 1)} disabled={i === chapters.length - 1} className="text-muted-foreground disabled:opacity-30 hover:text-foreground"><ArrowDown className="w-4 h-4" /></button>
                </div>
                <Link to={`/dashboard/story/${id}/chapter/${c.id}`} className="flex-1 min-w-0">
                  <p className="font-medium text-sm truncate">{c.title}</p>
                  <div className="flex items-center gap-2 mt-0.5 text-xs text-muted-foreground">
                    {c.status === 'paid' ? <span className="flex items-center gap-1"><Lock className="w-3 h-3" /> ${Number(c.price || 0).toFixed(2)}</span> : <span>Free</span>}
                    <span>·</span>
                    <span>{c.published ? 'Published' : 'Draft'}</span>
                  </div>
                </Link>
                <button onClick={() => togglePublishChapter(c)} className={`text-xs px-2.5 py-1 rounded-full ${c.published ? 'bg-emerald-500/10 text-emerald-600' : 'bg-muted text-muted-foreground'}`}>
                  {c.published ? 'Unpublish' : 'Publish'}
                </button>
                <Link to={`/dashboard/story/${id}/chapter/${c.id}`}><Button variant="ghost" size="sm"><Pencil className="w-4 h-4" /></Button></Link>
                <button onClick={() => deleteChapter(c)} className="text-muted-foreground hover:text-destructive"><Trash2 className="w-4 h-4" /></button>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}
```

---

## `src/pages/StoryRecap.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { useParams, useSearchParams, Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, Sparkles } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function StoryRecap() {
  const { storyId } = useParams();
  const [params] = useSearchParams();
  const chapterId = params.get('chapter');
  const { user } = useCurrentUser();
  const [story, setStory] = useState(null);
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'Story Recap — Chapterly', description: 'Get a quick summary of where you left off in your story.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const s = await base44.entities.Story.get(storyId);
        if (!active) return;
        setStory(s);
        const convs = await base44.agents.listConversations({ agent_name: 'story_recap' });
        let conv = (convs || []).find((c) => c.metadata?.story_id === storyId);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'story_recap',
            metadata: { story_id: storyId, chapter_id: chapterId || null, name: 'Recap: ' + s.title },
          });
          const chapterPart = chapterId ? ' I am about to read the chapter with id ' + chapterId + '.' : '';
          const upTo = chapterId ? ' up to the chapter I am about to read' : '';
          const seed = 'I am returning to the story "' + s.title + '" (story id: ' + storyId + ').' + chapterPart + ' Please read this story and its published chapters, then give me a concise recap of the plot so far' + upTo + ' so I can pick up where I left off. Do not spoil anything beyond that point.';
          await base44.agents.addMessage(conv, { role: 'user', content: seed });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setStory(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [storyId, chapterId, user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <Sparkles className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">Story Recap</h1>
        <p className="text-sm text-muted-foreground">Sign in to get a quick summary of where you left off in any story.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to={chapterId ? '/read/' + chapterId : '/story/' + storyId} className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Back
      </Link>

      <div className="flex items-center gap-2">
        <Sparkles className="w-5 h-5 text-primary" />
        <div>
          <h1 className="font-heading text-xl font-semibold">Story Recap</h1>
          {story && <p className="text-sm text-muted-foreground">{story.title}</p>}
        </div>
      </div>

      <div ref={scrollRef} className="h-[60vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Preparing your recap…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Ask for a recap to get started.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask about the plot, characters…"
          rows={2}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/SubscriptionAssistant.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, CreditCard } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function SubscriptionAssistant() {
  const { user } = useCurrentUser();
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'Subscription Assistant — Chapterly', description: 'Get clear status updates on your active Chapterly subscriptions and membership.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const convs = await base44.agents.listConversations({ agent_name: 'subscription_status' });
        let conv = (convs || []).find((c) => c.metadata?.user_key === user.id);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'subscription_status',
            metadata: { user_key: user.id, name: 'Subscription Assistant' },
          });
          await base44.agents.addMessage(conv, { role: 'user', content: 'Hi! Can you give me a status update on my active subscriptions?' });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setConversation(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <CreditCard className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">Subscription Assistant</h1>
        <p className="text-sm text-muted-foreground">Sign in to get clear status updates on your active subscriptions and membership.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to="/membership" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Membership
      </Link>

      <div className="flex items-center gap-2">
        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
          <CreditCard className="w-5 h-5 text-primary" />
        </div>
        <div>
          <h1 className="font-heading text-xl font-semibold">Subscription Assistant</h1>
          <p className="text-sm text-muted-foreground">Status updates on your active subscriptions and membership</p>
        </div>
      </div>

      <div ref={scrollRef} className="h-[60vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Starting your assistant…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Ask about your subscriptions to get started.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask about your subscriptions…"
          rows={2}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/Support.jsx`

```javascript
import { Link } from 'react-router-dom';
import { Mail, Trash2, CreditCard, PenLine, HelpCircle } from 'lucide-react';
import LegalLayout from '@/components/LegalLayout';
import { useSeo } from '@/hooks/useSeo';

const SUPPORT_EMAIL = 'mariamalik13397@gmail.com';

const topics = [
  {
    icon: CreditCard,
    title: 'Payments, unlocks, and subscriptions',
    body: 'Paid chapters unlock immediately after checkout. Reader memberships renew until canceled — cancel any time from Membership. If a charge looks wrong or you were charged twice, email us with the date and the story or chapter name and we will review it.',
  },
  {
    icon: PenLine,
    title: 'Publishing and payouts',
    body: 'Publish from the write dashboard, then request a payout from Earnings once your balance reaches the minimum shown there. Payouts are sent to the method you choose and can be held while a charge is under review.',
  },
  {
    icon: HelpCircle,
    title: 'Reporting a story, chapter, or comment',
    body: 'Use the report button on the story or chapter page, or on a comment. Reports go to the Chapterly team for review. For urgent safety issues, email us directly.',
  },
  {
    icon: Trash2,
    title: 'Deleting your account and data',
    body: 'You can delete your account and personal details yourself at any time — open Profile, then choose Delete account. We remove your account and personal information; content you published may be anonymized or removed. If you cannot sign in and want your data deleted, email us from the address on your account and we will complete the deletion for you.',
  },
];

export default function Support() {
  useSeo({
    title: 'Support — Chapterly',
    description: 'Get help with Chapterly: payments, publishing and payouts, reporting content, and deleting your account.',
    url: '/support',
  });

  return (
    <LegalLayout
      title="Support"
      subtitle="Help with your Chapterly account, payments, publishing, and privacy requests."
      updated="November 2026"
    >
      <div className="rounded-xl border border-border/60 bg-muted/40 p-4 flex items-start gap-3">
        <Mail className="w-4 h-4 mt-0.5 text-muted-foreground shrink-0" />
        <div>
          <p className="font-medium text-foreground">Contact the Chapterly team</p>
          <p className="text-sm mt-1">
            <a href={`mailto:${SUPPORT_EMAIL}`}>{SUPPORT_EMAIL}</a> — include your account email and, for payment
            questions, the date and amount of the charge. We reply to support requests as quickly as we can.
          </p>
        </div>
      </div>

      <div className="space-y-5">
        {topics.map((t) => {
          const Icon = t.icon;
          return (
            <div key={t.title} className="flex items-start gap-3">
              <Icon className="w-4 h-4 mt-0.5 text-muted-foreground shrink-0" />
              <div>
                <h2 className="!mt-0">{t.title}</h2>
                <p>{t.body}</p>
              </div>
            </div>
          );
        })}
      </div>

      <h2>Account</h2>
      <p>
        You can sign in with email and password, Google, or Apple. If you forget your password, use the reset link on the
        sign-in page. To update your display name or profile details, open your{' '}
        <Link to="/profile">profile</Link>.
      </p>

      <h2>Policies</h2>
      <p>
        Read our <Link to="/privacy">Privacy Policy</Link> and <Link to="/terms">Terms of Service</Link>.
      </p>
    </LegalLayout>
  );
}
```

---

## `src/pages/Terms.jsx`

```javascript
import LegalLayout from '@/components/LegalLayout';
import { useSeo } from '@/hooks/useSeo';

export default function Terms() {
  useSeo({
    title: 'Terms of Service — Chapterly',
    description: 'The terms that govern reading, writing, and payments on Chapterly.',
    url: '/terms',
  });

  return (
    <LegalLayout
      title="Terms of Service"
      subtitle="These terms govern your use of Chapterly as a reader and as a writer. Please read them before you use the service."
      updated="November 2026"
    >
      <h2>Using Chapterly</h2>
      <p>
        You must be at least 13 years old to use Chapterly. If you create an account, you are responsible for keeping your
        password secure and for activity under your account. Provide accurate information and let us know about any
        unauthorized use. Chapterly may be used for personal, non-commercial reading unless you are publishing your own work.
      </p>

      <h2>Your content</h2>
      <ul>
        <li>You keep ownership of the stories, chapters, covers, comments, and research papers you publish.</li>
        <li>You grant Chapterly a non-exclusive, worldwide license to host, display, format, and distribute your content within the service, and to include short excerpts in previews, share cards, and discovery features.</li>
        <li>You confirm you have the rights to everything you publish. Do not post content that infringes someone else&apos;s copyright, impersonates a real person, or you do not have permission to share.</li>
        <li>You are responsible for your own content. We may remove content or restrict accounts that break these terms, including through reader reports.</li>
      </ul>

      <h2>Paid content, subscriptions, and tips</h2>
      <ul>
        <li>Some chapters are paid. Prices are shown before purchase and are charged through our payment providers.</li>
        <li>Unlocking a chapter grants you personal access to read it on Chapterly. It is not a resale or redistribution right.</li>
        <li>Reader memberships and writer subscriptions renew until canceled. You can cancel at any time and keep access until the end of the period you paid for.</li>
        <li>Tips are voluntary and support the writer directly.</li>
        <li>Because paid content is delivered immediately, purchases are generally final. If something went wrong with a charge or you were charged twice, contact us and we will review it.</li>
      </ul>

      <h2>Writers and payouts</h2>
      <ul>
        <li>Chapterly keeps a platform share of paid sales; the remainder is credited to the writer.</li>
        <li>Payouts are requested in the writer dashboard and are subject to the minimum amount and payment method shown there.</li>
        <li>We may withhold a payout while a charge is disputed, or when we are reviewing suspected fraud or policy violations.</li>
        <li>You are responsible for any tax on the income you earn on Chapterly.</li>
      </ul>

      <h2>Acceptable use</h2>
      <ul>
        <li>No harassment, hate speech, threats, or targeted abuse of other users.</li>
        <li>No sexual content involving minors, and no content that is illegal where it is published.</li>
        <li>No spam, scraping, automated account creation, or attempts to bypass paid access or platform fees.</li>
        <li>No uploading malware, or interfering with the operation or security of the service.</li>
      </ul>

      <h2>AI features</h2>
      <p>
        Chapterly offers AI writing help, story recaps, and assistants. Generated output may be inaccurate or unoriginal;
        you are responsible for reviewing anything you publish. Do not submit other people&apos;s private information to these tools.
      </p>

      <h2>Suspension and termination</h2>
      <p>
        You may delete your account at any time from Profile → Delete account. We may suspend or close an account that
        breaks these terms, or where we are required to by law. Where a suspension relates to paid content, we will handle
        pending balances fairly.
      </p>

      <h2>Service availability</h2>
      <p>
        Chapterly is provided &quot;as is&quot;. Features may change, and the service may occasionally be unavailable for
        maintenance. To the extent permitted by law, we are not liable for indirect losses or for the content published by
        other users.
      </p>

      <h2>Changes to these terms</h2>
      <p>
        We may update these terms as the service evolves. Material changes will be announced in the app, and the date at the
        top of this page will change. Continuing to use Chapterly after a change means you accept the updated terms.
      </p>

      <h2>Contact</h2>
      <p>
        Questions about these terms? Reach the Chapterly team at{' '}
        <a href="mailto:mariamalik13397@gmail.com">mariamalik13397@gmail.com</a>.
      </p>
    </LegalLayout>
  );
}
```

---

## `src/pages/TipAssistant.jsx`

```javascript
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ArrowLeft, Send, Gift } from 'lucide-react';
import AgentMessage from '@/components/AgentMessage';
import { useSeo } from '@/hooks/useSeo';

export default function TipAssistant() {
  const { user } = useCurrentUser();
  const [conversation, setConversation] = useState(null);
  const [messages, setMessages] = useState([]);
  const [input, setInput] = useState('');
  const [sending, setSending] = useState(false);
  const [loading, setLoading] = useState(true);
  const scrollRef = useRef(null);

  useSeo({ title: 'Tip Assistant — Chapterly', description: 'Review and manage your tip contributions to writers on Chapterly.' });

  useEffect(() => {
    let active = true;
    (async () => {
      if (!user) { setLoading(false); return; }
      try {
        const convs = await base44.agents.listConversations({ agent_name: 'tip_manager' });
        let conv = (convs || []).find((c) => c.metadata?.user_key === user.id);
        if (!conv) {
          conv = await base44.agents.createConversation({
            agent_name: 'tip_manager',
            metadata: { user_key: user.id, name: 'Tip Assistant' },
          });
          await base44.agents.addMessage(conv, { role: 'user', content: 'Hi! Can you show me my tip contributions so far?' });
        }
        if (active) {
          setConversation(conv);
          setMessages(conv.messages || []);
        }
      } catch {
        if (active) setConversation(null);
      } finally {
        if (active) setLoading(false);
      }
    })();
    return () => { active = false; };
  }, [user]);

  useEffect(() => {
    if (!conversation) return;
    const unsub = base44.agents.subscribeToConversation(conversation.id, (data) => {
      setMessages(data.messages || []);
    });
    return () => unsub();
  }, [conversation]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages]);

  const send = async () => {
    const text = input.trim();
    if (!text || !conversation || sending) return;
    setSending(true);
    setInput('');
    try {
      await base44.agents.addMessage(conversation, { role: 'user', content: text });
    } catch { /* subscription surfaces errors */ }
    setSending(false);
  };

  if (!user) {
    return (
      <div className="max-w-md mx-auto text-center space-y-3 pt-16">
        <Gift className="w-8 h-8 text-primary mx-auto" />
        <h1 className="font-heading text-xl font-semibold">Tip Assistant</h1>
        <p className="text-sm text-muted-foreground">Sign in to review and manage your tip contributions to writers.</p>
        <Button asChild className="rounded-full"><Link to="/login">Sign in</Link></Button>
      </div>
    );
  }

  return (
    <div className="max-w-2xl mx-auto space-y-4">
      <Link to="/library" className="inline-flex items-center gap-1.5 text-sm text-muted-foreground hover:text-foreground">
        <ArrowLeft className="w-4 h-4" /> Library
      </Link>

      <div className="flex items-center gap-2">
        <div className="w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center">
          <Gift className="w-5 h-5 text-primary" />
        </div>
        <div>
          <h1 className="font-heading text-xl font-semibold">Tip Assistant</h1>
          <p className="text-sm text-muted-foreground">Review and manage your tip contributions to writers</p>
        </div>
      </div>

      <div ref={scrollRef} className="h-[60vh] overflow-y-auto space-y-3 rounded-xl border border-border/60 bg-card p-4 scroll-touch">
        {loading && <p className="text-sm text-muted-foreground text-center mt-8">Starting your assistant…</p>}
        {!loading && messages.length === 0 && <p className="text-sm text-muted-foreground text-center mt-8">Ask about your tips to get started.</p>}
        {messages.map((m, i) => <AgentMessage key={i} message={m} />)}
      </div>

      <div className="flex gap-2">
        <Textarea
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Ask about your tip contributions…"
          rows={2}
          className="resize-none"
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
        />
        <Button onClick={send} size="sm" className="self-end rounded-full" disabled={sending || !conversation}>
          <Send className="w-4 h-4" />
        </Button>
      </div>
    </div>
  );
}
```

---

## `src/pages/WriterDashboard.jsx`

```javascript
import { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { base44 } from '@/api/base44Client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Button } from '@/components/ui/button';
import { Image } from '@/components/ui/image';
import { Plus, BookOpen, Users, FileText, Eye, Heart, MessageSquare, Wallet, GraduationCap, Quote, Sparkles, BarChart3, Instagram, Star } from 'lucide-react';
import EarningsChart from '@/components/EarningsChart';
import ImportStoryButton from '@/components/ImportStoryButton';
import WordCountProgress from '@/components/WordCountProgress';
import WriterAnalytics from '@/components/WriterAnalytics';
import WeeklyLeaderboard from '@/components/WeeklyLeaderboard';
import StoryRatingsOverview from '@/components/reviews/StoryRatingsOverview';

export default function WriterDashboard() {
  const { user } = useCurrentUser();
  const [stories, setStories] = useState([]);
  const [stats, setStats] = useState({});
  const [engagement, setEngagement] = useState({ likes: [], comments: [], follows: [], ratings: [] });

  const load = async () => {
    if (!user) return;
    try {
      const s = await base44.entities.Story.filter({ created_by_id: user.id }, '-created_date');
      setStories(s);
      if (s.length === 0) return;

      // Fetch follows once (writer-level, same across all stories)
      const follows = await base44.entities.Follow.filter({ writer_id: user.id });
      const allLikes = [];
      const allComments = [];
      const allRatings = [];

      const results = await Promise.all(
        s.map(async (st) => {
          const [ch, likes, storyRatings] = await Promise.all([
            base44.entities.Chapter.filter({ story_id: st.id }),
            base44.entities.Like.filter({ target_type: 'story', target_id: st.id }),
            base44.entities.Rating.filter({ story_id: st.id }).catch(() => []),
          ]);
          allLikes.push(...likes);
          allRatings.push(...storyRatings);

          const commentCounts = await Promise.all(
            ch.map(async (c) => {
              const comments = await base44.entities.Comment.filter({ chapter_id: c.id }).catch(() => []);
              allComments.push(...comments);
              return comments.length;
            })
          );

          const views = ch.reduce((sum, c) => sum + (c.views || 0), 0);
          const comments = commentCounts.reduce((sum, c) => sum + c, 0);
          return {
            id: st.id,
            stats: {
              chapters: ch.length,
              published: ch.filter((c) => c.published).length,
              followers: follows.length,
              views,
              likes: likes.length,
              comments,
              ratings: storyRatings.length,
              rating: storyRatings.length
                ? storyRatings.reduce((sum, r) => sum + (r.value || 0), 0) / storyRatings.length
                : 0,
            },
          };
        })
      );

      const map = {};
      results.forEach(({ id, stats }) => { map[id] = stats; });
      setStats(map);
      setEngagement({ likes: allLikes, comments: allComments, follows, ratings: allRatings });
    } catch (e) {}
  };

  useEffect(() => { load(); }, [user]);

  return (
    <div className="space-y-8">
      <div className="flex items-center justify-between gap-4">
        <div>
          <h1 className="font-heading text-3xl font-semibold tracking-tight">Writer dashboard</h1>
          <p className="text-muted-foreground text-sm mt-1">Create stories, write chapters, and set your prices.</p>
        </div>
        <div className="flex items-center gap-2">
          <Link to="/ria">
            <Button variant="outline" className="rounded-full">
              <Sparkles className="w-4 h-4 mr-1.5" /> Ria
            </Button>
          </Link>
          <Link to="/dashboard/engagement">
            <Button variant="outline" className="rounded-full">
              <BarChart3 className="w-4 h-4 mr-1.5" /> Engagement
            </Button>
          </Link>
          <Link to="/dashboard/instagram">
            <Button variant="outline" className="rounded-full">
              <Instagram className="w-4 h-4 mr-1.5" /> Instagram
            </Button>
          </Link>
          <Link to="/earnings">
            <Button variant="outline" className="rounded-full">
              <Wallet className="w-4 h-4 mr-1.5" /> Earnings
            </Button>
          </Link>
          <ImportStoryButton />
          <Link to="/dashboard/story/new">
            <Button className="rounded-full">
              <Plus className="w-4 h-4 mr-1.5" /> New story
            </Button>
          </Link>
        </div>
      </div>

      <div className="grid sm:grid-cols-2 gap-3">
        <Link
          to="/research"
          className="flex items-center justify-between gap-4 p-4 rounded-xl border border-border/60 bg-muted/30 hover:bg-muted/60 transition"
        >
          <div>
            <h2 className="font-heading text-base font-semibold flex items-center gap-2">
              <GraduationCap className="w-4 h-4" /> Research papers
            </h2>
            <p className="text-xs text-muted-foreground mt-0.5">Publish research articles and get authentic, citable references.</p>
          </div>
          <span className="text-sm text-muted-foreground">Open →</span>
        </Link>
        <Link
          to="/dashboard/citations"
          className="flex items-center justify-between gap-4 p-4 rounded-xl border border-border/60 bg-muted/30 hover:bg-muted/60 transition"
        >
          <div>
            <h2 className="font-heading text-base font-semibold flex items-center gap-2">
              <Quote className="w-4 h-4" /> My citations
            </h2>
            <p className="text-xs text-muted-foreground mt-0.5">Download formal citation blocks for your published papers.</p>
          </div>
          <span className="text-sm text-muted-foreground">Open →</span>
        </Link>
      </div>

      <WeeklyLeaderboard />

      <EarningsChart />

      <WordCountProgress />

      <WriterAnalytics stories={stories} stats={stats} engagement={engagement} />

      <StoryRatingsOverview stories={stories} ratings={engagement.ratings || []} />

      {stories.length === 0 ? (
        <div className="rounded-2xl border border-dashed border-border p-12 text-center">
          <BookOpen className="w-8 h-8 mx-auto text-muted-foreground" />
          <p className="mt-3 text-sm text-muted-foreground">You haven't published any stories yet.</p>
          <Link to="/dashboard/story/new">
            <Button className="rounded-full mt-4">Create your first story</Button>
          </Link>
        </div>
      ) : (
        <div className="space-y-3">
          {stories.map((s) => (
            <Link
              key={s.id}
              to={`/dashboard/story/${s.id}`}
              className="flex items-center gap-4 p-3 rounded-xl border border-border/60 hover:bg-muted/40 transition"
            >
              <div className="w-12 h-16 rounded-md overflow-hidden bg-muted shrink-0">
                {s.cover_url ? <Image src={s.cover_url} fittingType="fill" className="w-full h-full" /> : null}
              </div>
              <div className="flex-1 min-w-0">
                <h3 className="font-heading font-semibold truncate">{s.title}</h3>
                <span className={`text-[11px] px-1.5 py-0.5 rounded ${s.status === 'published' ? 'bg-emerald-500/10 text-emerald-600' : 'bg-muted text-muted-foreground'}`}>
                  {s.status}
                </span>
              </div>
              <div className="hidden sm:flex items-center gap-5 text-sm text-muted-foreground">
                <span className="flex items-center gap-1.5"><Eye className="w-4 h-4" /> {stats[s.id]?.views ?? 0}</span>
                <span className="flex items-center gap-1.5">
                  <Star className="w-4 h-4" />
                  {stats[s.id]?.ratings ? `${stats[s.id].rating.toFixed(1)} (${stats[s.id].ratings})` : '—'}
                </span>
                <span className="flex items-center gap-1.5"><Heart className="w-4 h-4" /> {stats[s.id]?.likes ?? 0}</span>
                <span className="flex items-center gap-1.5"><MessageSquare className="w-4 h-4" /> {stats[s.id]?.comments ?? 0}</span>
                <span className="flex items-center gap-1.5"><FileText className="w-4 h-4" /> {stats[s.id]?.published ?? 0}/{stats[s.id]?.chapters ?? 0}</span>
                <span className="flex items-center gap-1.5"><Users className="w-4 h-4" /> {stats[s.id]?.followers ?? 0}</span>
              </div>
            </Link>
          ))}
        </div>
      )}
    </div>
  );
}
```

---

## `src/utils/index.ts`

```typescript
export function createPageUrl(pageName: string) {
    return '/' + pageName.replace(/ /g, '-');
}
```

---

## `public/.well-known/assetlinks.json`

```javascript
[
  {
    "relation": ["delegate_permission/common.handle_all_urls"],
    "target": {
      "namespace": "android_app",
      "package_name": "com.baseAPPID.app",
      "sha256_cert_fingerprints": [
        "SHA256_FINGERPRINT_FROM_PLAY_CONSOLE"
      ]
    }
  }
]

```

---

## `public/apple-app-site-association`

```text
{
  "applinks": {
    "apps": [],
    "details": [
      {
        "appIDs": ["TEAMID.com.baseAPPID.app"],
        "components": [
          { "/": "/*" }
        ]
      }
    ]
  },
  "webcredentials": {
    "apps": ["TEAMID.com.baseAPPID.app"]
  }
}

```

---

## `public/manifest.json`

```javascript
{
  "name": "Chapterly — Read & write serialized fiction",
  "short_name": "Chapterly",
  "description": "Discover, follow, and support independent storytellers with a seamless, serialized reading experience.",
  "start_url": "/",
  "scope": "/",
  "display": "standalone",
  "orientation": "portrait",
  "background_color": "#f4fbf4",
  "theme_color": "#5a91f6",
  "icons": [
    {
      "src": "https://media.base44.com/images/public/6a83585d06d790bc1c169856/689caf1d5_logo.png",
      "sizes": "any",
      "type": "image/png",
      "purpose": "any"
    },
    {
      "src": "https://media.base44.com/images/public/6a83585d06d790bc1c169856/689caf1d5_logo.png",
      "sizes": "any",
      "type": "image/png",
      "purpose": "maskable"
    }
  ]
}

```

