This commit is contained in:
2026-06-08 16:42:04 -04:00
commit 8bda14ab63
179 changed files with 48104 additions and 0 deletions

240
src/app/about/page.tsx Normal file
View File

@@ -0,0 +1,240 @@
import React from "react";
import Link from "next/link";
import type { Metadata } from "next";
import { APP_NAME, BETA_DISCLAIMER } from "@/lib/constants";
export const metadata: Metadata = {
title: "About",
description: `Learn about ${APP_NAME} — our mission, methodology, data sources, and limitations. Open-source plant disease identification.`,
};
/* ─── FAQ accordion (server component with details/summary) ─── */
const faqs = [
{
q: "How accurate is the disease identification?",
a: "Our model has been trained on 500K+ labeled plant disease images covering 300+ plant species. Accuracy varies by plant and disease type, with confidence scores provided for each diagnosis. The model performs best on common diseases with visible foliar symptoms. We recommend using multiple sources of information for critical plant health decisions.",
},
{
q: "Which plants are supported?",
a: "We currently have detailed disease data for 8+ common garden plants including tomato, basil, rose, monstera, snake plant, bell pepper, lavender, and sunflower. We are actively adding more plants. Browse our full catalog on the Browse Plants page.",
},
{
q: "Can I use this for commercial farming?",
a: "While our database covers common agricultural plants like tomatoes and peppers, the tool is designed primarily for home gardeners and small-scale growers. For commercial agriculture, we recommend consulting with local extension services, certified crop advisors, and using laboratory testing for definitive diagnosis.",
},
{
q: "How does the AI model work?",
a: "The model uses a convolutional neural network (CNN) trained on thousands of labeled plant disease images. When you upload a photo, the model analyzes visual patterns — leaf spots, discoloration, wilting patterns, and other symptoms — then matches them against known disease signatures. The output includes the most likely diagnosis with a confidence percentage.",
},
{
q: "Is my data private?",
a: "Yes. Uploaded images are processed temporarily for analysis and are not permanently stored or used for training without explicit consent. We do not share or sell user data. See our privacy policy for details.",
},
{
q: "What if my plant has a disease that's not in the database?",
a: "If the model cannot identify the disease with sufficient confidence, it will indicate that the condition is not recognized. In this case, we recommend consulting a local plant pathologist, master gardener, or agricultural extension service. You can also contribute by submitting data to help us expand our knowledge base.",
},
];
function FAQAccordion() {
return (
<div className="space-y-3">
{faqs.map((faq, i) => (
<details
key={i}
className="group rounded-xl border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-900 overflow-hidden"
>
<summary className="flex items-center justify-between gap-4 px-5 py-4 cursor-pointer list-none text-sm font-medium text-zinc-900 dark:text-zinc-100 hover:bg-zinc-50 dark:hover:bg-zinc-800 transition-colors">
{faq.q}
<span
className="shrink-0 text-zinc-400 group-open:rotate-180 transition-transform"
aria-hidden="true"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="20"
height="20"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
<path d="m6 9 6 6 6-6" />
</svg>
</span>
</summary>
<div className="px-5 pb-4 pt-0">
<p className="text-sm text-zinc-600 dark:text-zinc-300 leading-relaxed">{faq.a}</p>
</div>
</details>
))}
</div>
);
}
/* ─── About Page ─── */
export default function AboutPage() {
return (
<div className="mx-auto max-w-3xl px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
{/* Page header */}
<div className="text-center mb-12">
<span className="text-6xl block mb-4" aria-hidden="true">
🌱
</span>
<h1 className="text-3xl sm:text-4xl font-bold text-zinc-900 dark:text-zinc-100">
About {APP_NAME}
</h1>
<p className="mt-3 text-lg text-zinc-500 dark:text-zinc-400 max-w-lg mx-auto">
Making plant disease identification accessible to every gardener.
</p>
</div>
{/* Mission */}
<section className="mb-12">
<h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100 mb-4">Our Mission</h2>
<div className="prose prose-sm max-w-none text-zinc-600 dark:text-zinc-300 space-y-4">
<p>
Gardening is a labor of love — and watching a plant struggle with an unknown disease is
heartbreaking. Our mission is to put the power of AI-powered disease identification into
every gardener&apos;s pocket, for free.
</p>
<p>
{APP_NAME} was built by a team of gardeners and developers who were frustrated with
vague, generic plant disease advice. We wanted hyper-specific diagnoses — not just
&ldquo;your plant has a fungus&rdquo; but &ldquo;your tomato has Late Blight caused by
Phytophthora infestans, and here&apos;s exactly how to treat it.&rdquo;
</p>
</div>
</section>
{/* How the model works */}
<section className="mb-12">
<h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100 mb-4">
How the Model Works
</h2>
<div className="prose prose-sm max-w-none text-zinc-600 dark:text-zinc-300 space-y-4">
<p>
The identification engine uses a deep convolutional neural network trained on a dataset
of <strong>500,000+ labeled plant disease images</strong> spanning 300+ plant species.
When you upload a photo:
</p>
<ol className="list-decimal list-inside space-y-2">
<li>
<strong>Preprocessing</strong> — The image is normalized and analyzed for relevant
regions (leaves, stems, fruit).
</li>
<li>
<strong>Feature extraction</strong> — The model identifies visual patterns: lesion
shape, color, margin type, texture, and distribution.
</li>
<li>
<strong>Classification</strong> — Patterns are matched against known disease
signatures, producing a ranked list of possible diagnoses with confidence scores.
</li>
<li>
<strong>Recommendation</strong> — The top diagnosis is paired with treatment steps,
prevention tips, and severity information from our curated knowledge base.
</li>
</ol>
</div>
</section>
{/* Data sources */}
<section className="mb-12">
<h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100 mb-4">
Data Sources
</h2>
<div className="prose prose-sm max-w-none text-zinc-600 dark:text-zinc-300 space-y-4">
<p>
Our disease knowledge base is curated from peer-reviewed plant pathology resources,
including:
</p>
<ul className="list-disc list-inside space-y-1">
<li>University agricultural extension publications</li>
<li>Peer-reviewed plant pathology journals</li>
<li>USDA plant disease databases</li>
<li>Contributions from the open-source gardening community</li>
</ul>
<p>
We prioritize evidence-based, actionable information. Disease descriptions, treatments,
and prevention tips are reviewed for accuracy before inclusion.
</p>
</div>
</section>
{/* Limitations */}
<section className="mb-12">
<div className="rounded-xl border border-warning-amber-200 dark:border-warning-amber-800 bg-warning-amber-50 dark:bg-warning-amber-950/50 p-6">
<h2 className="text-xl font-semibold text-warning-amber-800 dark:text-warning-amber-300 mb-3 flex items-center gap-2">
<span aria-hidden="true">⚠️</span>
Limitations &amp; Disclaimer
</h2>
<div className="text-sm text-warning-amber-700 dark:text-warning-amber-400 space-y-3">
<p>{BETA_DISCLAIMER}</p>
<p>
The AI model may not accurately identify all diseases, especially unusual
presentations, early-stage infections, or diseases outside its training data. Always
confirm diagnoses with professional resources for critical decisions.
</p>
<p>
This tool is <strong>not</strong> FDA-approved or certified as a medical/agricultural
diagnostic device. It is an educational assistive tool.
</p>
</div>
</div>
</section>
{/* Open source */}
<section className="mb-12">
<h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100 mb-4">
Open Source &amp; Contributions
</h2>
<div className="prose prose-sm max-w-none text-zinc-600 dark:text-zinc-300 space-y-4">
<p>
{APP_NAME} is free and open source. We believe plant health information should be
accessible to everyone. The entire project is available on GitHub, and we welcome
contributions!
</p>
<p>You can contribute by:</p>
<ul className="list-disc list-inside space-y-1">
<li>Adding new plant and disease data</li>
<li>Improving the AI model with training data</li>
<li>Reporting bugs or suggesting features</li>
<li>Translating content to other languages</li>
<li>Sharing plant photos (with permission) for model improvement</li>
</ul>
<p>
<Link
href="https://github.com/plant-health-id"
className="text-leaf-green-600 hover:text-leaf-green-700 dark:text-leaf-green-400 dark:hover:text-leaf-green-300 font-medium underline underline-offset-2"
target="_blank"
rel="noopener noreferrer"
>
View on GitHub →
</Link>
</p>
</div>
</section>
{/* FAQ */}
<section className="mb-8">
<h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100 mb-6">
Frequently Asked Questions
</h2>
<FAQAccordion />
</section>
{/* Back to home */}
<div className="text-center pt-8 border-t border-zinc-200 dark:border-zinc-800">
<Link
href="/"
className="inline-flex items-center gap-2 text-sm font-medium text-leaf-green-600 hover:text-leaf-green-700 dark:text-leaf-green-400 dark:hover:text-leaf-green-300 transition-colors"
>
<span aria-hidden="true">←</span> Back to home
</Link>
</div>
</div>
);
}

View File

@@ -0,0 +1,41 @@
import { NextRequest, NextResponse } from "next/server";
import { getDiseaseWithPlant, getLookalikeDiseases } from "@/lib/api/diseases-db";
interface RouteParams {
params: Promise<{ id: string }>;
}
/**
* GET /api/diseases/[id]
* Get a single disease with its associated plant and lookalike diseases.
*/
export async function GET(_request: NextRequest, { params }: RouteParams): Promise<NextResponse> {
const { id } = await params;
console.log(`[API] GET /api/diseases/${id}`);
const result = await getDiseaseWithPlant(id);
if (!result) {
return NextResponse.json(
{
error: "Not Found",
message: `Disease with ID "${id}" not found`,
status: 404,
},
{ status: 404, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
const lookalikes = await getLookalikeDiseases(id);
return NextResponse.json(
{
disease: result.disease,
plant: result.plant,
lookalikes,
},
{ headers: { "Cache-Control": "public, max-age=3600" } },
);
}

View File

@@ -0,0 +1,124 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { GET } from "./route";
import * as diseasesLib from "@/lib/api/diseases-db";
// Mock the diseases library
vi.mock("@/lib/api/diseases-db", () => ({
listDiseases: vi.fn(() => Promise.resolve([])),
}));
describe("GET /api/diseases", () => {
const createRequest = (searchParams: string) => {
const url = new URL(`http://localhost/api/diseases${searchParams}`);
const req = new Request(url);
(req as any).nextUrl = url;
return req;
};
beforeEach(() => {
vi.clearAllMocks();
});
it("returns all diseases with no filters", async () => {
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "early-blight", name: "Early Blight" },
{ id: "late-blight", name: "Late Blight" },
]);
const response = await GET(createRequest(""));
expect(response.status).toBe(200);
const body = await response.json();
expect(body.diseases).toHaveLength(2);
expect(body.total).toBe(2);
});
it("filters diseases by plantId", async () => {
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "early-blight", name: "Early Blight", plantId: "tomato" },
]);
const response = await GET(createRequest("?plantId=tomato"));
expect(response.status).toBe(200);
});
it("filters diseases by search term", async () => {
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "early-blight", name: "Early Blight" },
]);
const response = await GET(createRequest("?search=blight"));
expect(response.status).toBe(200);
});
it("filters diseases by causalAgentType", async () => {
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "early-blight", name: "Early Blight", causalAgentType: "fungal" },
]);
const response = await GET(createRequest("?causalAgentType=fungal"));
expect(response.status).toBe(200);
});
it("filters diseases by severity", async () => {
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "early-blight", name: "Early Blight", severity: "moderate" },
]);
const response = await GET(createRequest("?severity=moderate"));
expect(response.status).toBe(200);
});
it("returns 400 for empty search term", async () => {
const response = await GET(createRequest("?search="));
expect(response.status).toBe(400);
const body = await response.json();
expect(body.error).toBe("Bad Request");
});
it("returns 400 for invalid causalAgentType", async () => {
const response = await GET(createRequest("?causalAgentType=invalid"));
expect(response.status).toBe(400);
const body = await response.json();
expect(body.message).toMatch(/Invalid causalAgentType/i);
});
it("returns 400 for invalid severity", async () => {
const response = await GET(createRequest("?severity=invalid"));
expect(response.status).toBe(400);
const body = await response.json();
expect(body.message).toMatch(/Invalid severity/i);
});
it("accepts valid causalAgentTypes", async () => {
const validTypes = ["fungal", "bacterial", "viral", "environmental"];
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([]);
for (const type of validTypes) {
const response = await GET(createRequest(`?causalAgentType=${type}`));
expect(response.status).toBe(200);
}
});
it("accepts valid severities", async () => {
const validSeverities = ["low", "moderate", "high", "critical"];
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([]);
for (const severity of validSeverities) {
const response = await GET(createRequest(`?severity=${severity}`));
expect(response.status).toBe(200);
}
});
it("returns cache control header", async () => {
(diseasesLib.listDiseases as ReturnType<typeof vi.fn>).mockResolvedValue([]);
const response = await GET(createRequest(""));
const cacheControl = response.headers.get("Cache-Control");
expect(cacheControl).toContain("max-age=3600");
});
});

View File

@@ -0,0 +1,71 @@
import { NextRequest, NextResponse } from "next/server";
import { listDiseases } from "@/lib/api/diseases-db";
/**
* GET /api/diseases
* List all diseases with optional filters.
* Query params: ?plantId=<id> & ?search=<term> & ?causalAgentType=<type> & ?severity=<level>
*/
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const plantId = searchParams.get("plantId");
const search = searchParams.get("search");
const causalAgentType = searchParams.get("causalAgentType") as
| "fungal"
| "bacterial"
| "viral"
| "environmental"
| null;
const severity = searchParams.get("severity") as "low" | "moderate" | "high" | "critical" | null;
// Validate search param
if (search !== null && search.trim().length === 0) {
return NextResponse.json(
{ error: "Bad Request", message: "Search term cannot be empty", status: 400 },
{ status: 400, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
// Validate causalAgentType param
const validCausalAgentTypes = ["fungal", "bacterial", "viral", "environmental"];
if (causalAgentType !== null && !validCausalAgentTypes.includes(causalAgentType)) {
return NextResponse.json(
{
error: "Bad Request",
message: `Invalid causalAgentType. Must be one of: ${validCausalAgentTypes.join(", ")}`,
status: 400,
},
{ status: 400, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
// Validate severity param
const validSeverities = ["low", "moderate", "high", "critical"];
if (severity !== null && !validSeverities.includes(severity)) {
return NextResponse.json(
{
error: "Bad Request",
message: `Invalid severity. Must be one of: ${validSeverities.join(", ")}`,
status: 400,
},
{ status: 400, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
console.log(
`[API] GET /api/diseases plantId="${plantId}" search="${search}" causalAgentType="${causalAgentType}" severity="${severity}"`,
);
const results = await listDiseases({
plantId: plantId || undefined,
search: search || undefined,
causalAgentType: causalAgentType || undefined,
severity: severity || undefined,
});
return NextResponse.json(
{ diseases: results, total: results.length },
{ headers: { "Cache-Control": "public, max-age=3600" } },
);
}

View File

@@ -0,0 +1,143 @@
import { NextResponse } from "next/server";
import { getDb } from "@/lib/db/index";
import { flaggedContent, plants, diseases } from "@/lib/db/schema";
import { inArray, sql } from "drizzle-orm";
/**
* GET /api/flag/report
*
* Returns all flagged content grouped by content type, with resolved
* plant/disease names for readability. Used by the generate-flagged-report script.
*
* Query params:
* minFlags - Optional minimum flag count to include (default: 1)
*/
export async function GET(request: Request) {
try {
const { searchParams } = new URL(request.url);
const minFlags = parseInt(searchParams.get("minFlags") ?? "1", 10);
const db = getDb();
// Get all flagged entries
const rows = await db
.select()
.from(flaggedContent)
.where(sql`flag_count >= ${minFlags}`)
.orderBy(flaggedContent.contentType, flaggedContent.flagCount);
if (rows.length === 0) {
return NextResponse.json({
total: 0,
groups: {},
items: [],
});
}
// Resolve plant/disease names
const plantIds = new Set<string>();
const diseaseIds = new Set<string>();
for (const row of rows) {
if (row.contentType === "plant_image") {
plantIds.add(row.contentId);
} else {
diseaseIds.add(row.contentId);
}
}
// Fetch plant names
const plantMap = new Map<string, string>();
if (plantIds.size > 0) {
const plantRows = await db
.select({ id: plants.id, name: plants.commonName })
.from(plants)
.where(inArray(plants.id, [...plantIds]));
for (const p of plantRows) {
plantMap.set(p.id, p.name);
}
}
// Fetch disease names + their plant references
const diseaseMap = new Map<string, { name: string; plantId: string }>();
if (diseaseIds.size > 0) {
const diseaseRows = await db
.select({
id: diseases.id,
name: diseases.name,
plantId: diseases.plantId,
})
.from(diseases)
.where(inArray(diseases.id, [...diseaseIds]));
for (const d of diseaseRows) {
diseaseMap.set(d.id, { name: d.name, plantId: d.plantId });
}
// Fetch plants for diseases that we don't already have
for (const d of diseaseRows) {
if (!plantMap.has(d.plantId)) {
plantIds.add(d.plantId);
}
}
if (plantIds.size > 0) {
const plantRows = await db
.select({ id: plants.id, name: plants.commonName })
.from(plants)
.where(inArray(plants.id, [...plantIds]));
for (const p of plantRows) {
plantMap.set(p.id, p.name);
}
}
}
// Group by content type
const groups: Record<string, Array<Record<string, unknown>>> = {};
for (const row of rows) {
const type = row.contentType;
if (!groups[type]) groups[type] = [];
let label = row.contentId;
if (type === "plant_image") {
label = plantMap.get(row.contentId) ?? row.contentId;
} else {
const disease = diseaseMap.get(row.contentId);
if (disease) {
const plantName = plantMap.get(disease.plantId) ?? disease.plantId;
label = `${disease.name} (on ${plantName})`;
}
}
groups[type].push({
id: row.id,
contentType: row.contentType,
contentId: row.contentId,
fieldName: row.fieldName,
label,
notes: row.notes,
flagCount: row.flagCount,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
});
}
return NextResponse.json({
total: rows.length,
groups,
items: rows.map((row) => ({
id: row.id,
contentType: row.contentType,
contentId: row.contentId,
fieldName: row.fieldName,
notes: row.notes,
flagCount: row.flagCount,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
})),
});
} catch (err) {
console.error("[Flag Report] Error fetching flagged content:", err);
return NextResponse.json(
{ error: "Internal Server Error", message: "Failed to fetch flagged content", status: 500 },
{ status: 500 },
);
}
}

148
src/app/api/flag/route.ts Normal file
View File

@@ -0,0 +1,148 @@
import { NextRequest, NextResponse } from "next/server";
import { eq, and } from "drizzle-orm";
import { getDb } from "@/lib/db/index";
import { flaggedContent } from "@/lib/db/schema";
import { v4 as uuidv4 } from "uuid";
/**
* Content types that can be flagged for manual review.
*/
const VALID_CONTENT_TYPES = [
"plant_image",
"disease_image",
"disease_description",
"disease_symptoms",
"disease_causes",
"disease_treatment",
"disease_prevention",
] as const;
type FlagContentType = (typeof VALID_CONTENT_TYPES)[number];
interface FlagRequestBody {
contentType: FlagContentType;
contentId: string;
fieldName: string;
notes?: string;
}
/**
* POST /api/flag
*
* Flag content for manual review. If the same content_type + content_id + field_name
* combination already exists, increments the flag_count. Otherwise creates a new entry.
*
* Body:
* contentType - Type of content being flagged
* contentId - The ID of the plant or disease
* fieldName - The specific field name (e.g., "image", "symptoms")
* notes - Optional notes/reason for flagging
*/
export async function POST(request: NextRequest) {
try {
const body: FlagRequestBody = await request.json();
// ── Validate required fields ──
if (!body.contentType || !VALID_CONTENT_TYPES.includes(body.contentType)) {
return NextResponse.json(
{
error: "Bad Request",
message: `Invalid contentType. Must be one of: ${VALID_CONTENT_TYPES.join(", ")}`,
status: 400,
},
{ status: 400 },
);
}
if (
!body.contentId ||
typeof body.contentId !== "string" ||
body.contentId.trim().length === 0
) {
return NextResponse.json(
{ error: "Bad Request", message: "contentId is required", status: 400 },
{ status: 400 },
);
}
if (
!body.fieldName ||
typeof body.fieldName !== "string" ||
body.fieldName.trim().length === 0
) {
return NextResponse.json(
{ error: "Bad Request", message: "fieldName is required", status: 400 },
{ status: 400 },
);
}
const db = getDb();
// ── Check if this item was already flagged ──
const existing = await db
.select()
.from(flaggedContent)
.where(
and(
eq(flaggedContent.contentType, body.contentType),
eq(flaggedContent.contentId, body.contentId),
eq(flaggedContent.fieldName, body.fieldName),
),
)
.limit(1);
if (existing.length > 0) {
// Increment flag count and update timestamp
const current = existing[0];
await db
.update(flaggedContent)
.set({
flagCount: (current.flagCount ?? 0) + 1,
updatedAt: new Date().toISOString(),
...(body.notes ? { notes: body.notes } : {}),
})
.where(eq(flaggedContent.id, current.id));
return NextResponse.json({
success: true,
action: "incremented",
flagCount: (current.flagCount ?? 0) + 1,
message: "Flag count incremented. Thank you for your review input.",
});
}
// ── Create new flag entry ──
const id = uuidv4();
await db.insert(flaggedContent).values({
id,
contentType: body.contentType,
contentId: body.contentId,
fieldName: body.fieldName,
notes: body.notes ?? "",
flagCount: 1,
});
console.log(
`[Flag] New flag: type=${body.contentType} id=${body.contentId} field=${body.fieldName}`,
);
return NextResponse.json(
{
success: true,
action: "created",
flagCount: 1,
message: "Content flagged for manual review. Thank you!",
},
{ status: 201 },
);
} catch (err) {
console.error("[Flag] Error flagging content:", err);
return NextResponse.json(
{ error: "Internal Server Error", message: "Failed to flag content", status: 500 },
{ status: 500 },
);
}
}

View File

@@ -0,0 +1,27 @@
import { describe, it, expect } from "vitest";
import { GET } from "./route";
describe("GET /api/health", () => {
it("returns 200 with status ok", async () => {
const response = await GET();
expect(response.status).toBe(200);
const body = await response.json();
expect(body.status).toBe("ok");
expect(body.timestamp).toBeDefined();
});
it("returns valid ISO timestamp", async () => {
const response = await GET();
const body = await response.json();
const date = new Date(body.timestamp);
expect(date.toString()).not.toBe("Invalid Date");
});
it("returns JSON content type", async () => {
const response = await GET();
const contentType = response.headers.get("content-type");
expect(contentType).toContain("application/json");
});
});

View File

@@ -0,0 +1,13 @@
import { NextResponse } from "next/server";
/**
* Health-check endpoint.
* Returns 200 with status and current timestamp.
* Used for deployment verification and load-balancer probes.
*/
export async function GET(): Promise<NextResponse> {
return NextResponse.json({
status: "ok",
timestamp: new Date().toISOString(),
});
}

View File

@@ -0,0 +1,241 @@
/**
* Integration tests for app/api/identify/route.ts
*
* These tests call the actual running dev server via fetch.
* Run with: `npm run dev` in one terminal, then `npx vitest run src/app/api/identify/identify.test.ts`
*
* Tests:
* - POST /api/identify with valid imageId returns 200 with predictions array
* - POST /api/identify with invalid imageId returns 404
* - POST /api/identify with missing imageId returns 400
* - POST /api/identify with invalid JSON returns 400
* - Each prediction's diseaseId exists in knowledge base
* - Response includes inference timing metadata
* - Response includes demo_mode flag when using mock model
* - Predictions include lookalike cross-references
* - Predictions are sorted by confidence descending
*/
// @vitest-environment node
import { describe, it, expect, beforeAll } from "vitest";
import { getDiseaseById } from "@/lib/api/diseases-db";
const BASE_URL = process.env.TEST_BASE_URL || "http://localhost:3000";
// ─── Helpers ─────────────────────────────────────────────────────────────────
/**
* Create a test image buffer using sharp.
*/
async function createTestImage(
width: number,
height: number,
bg = { r: 34, g: 197, b: 94 },
): Promise<Buffer> {
const sharpMod = await import("sharp");
const sharp = sharpMod.default;
return sharp({
create: { width, height, channels: 3, background: bg },
})
.jpeg({ quality: 90 })
.toBuffer();
}
/**
* Upload a test image and return the imageId.
*/
async function uploadTestImage(): Promise<string> {
const buffer = await createTestImage(300, 300, { r: 34, g: 197, b: 94 });
const file = new File([buffer], "test.jpg", { type: "image/jpeg" });
const formData = new FormData();
formData.append("image", file);
const response = await fetch(`${BASE_URL}/api/upload`, {
method: "POST",
body: formData,
});
const data = await response.json();
expect(response.status).toBe(200);
return data.imageId;
}
/**
* Call the identify endpoint with a given imageId.
*/
async function callIdentify(imageId: string): Promise<{
status: number;
data: any;
ok: boolean;
}> {
const response = await fetch(`${BASE_URL}/api/identify`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ imageId }),
});
const data = await response.json();
return { status: response.status, data, ok: response.ok };
}
// ─── Tests ───────────────────────────────────────────────────────────────────
describe("POST /api/identify", () => {
let imageId: string;
beforeAll(async () => {
imageId = await uploadTestImage();
}, 15000);
it("returns 200 with predictions array for valid imageId", async () => {
const { status, data } = await callIdentify(imageId);
expect(status).toBe(200);
expect(data.predictions).toBeDefined();
expect(Array.isArray(data.predictions)).toBe(true);
expect(data.predictions.length).toBeGreaterThan(0);
}, 30000);
it("returns 404 for invalid imageId", async () => {
const { status, data } = await callIdentify("nonexistent-image-id");
expect(status).toBe(404);
expect(data.error).toBe("Image not found");
}, 15000);
it("returns 400 for missing imageId", async () => {
const response = await fetch(`${BASE_URL}/api/identify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({}),
});
const data = await response.json();
expect(response.status).toBe(400);
expect(data.error).toBe("Missing imageId");
}, 15000);
it("returns 400 for invalid JSON", async () => {
const response = await fetch(`${BASE_URL}/api/identify`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: "not json",
});
expect(response.status).toBe(400);
}, 15000);
it("response includes metadata with model, inferenceTimeMs, imageId", async () => {
const { data } = await callIdentify(imageId);
expect(data.metadata).toBeDefined();
expect(data.metadata.model).toBeDefined();
expect(typeof data.metadata.model).toBe("string");
expect(data.metadata.inferenceTimeMs).toBeDefined();
expect(typeof data.metadata.inferenceTimeMs).toBe("number");
expect(data.metadata.inferenceTimeMs).toBeGreaterThan(0);
expect(data.metadata.imageId).toBe(imageId);
}, 30000);
it("response includes demo_mode flag when using mock model", async () => {
const { data } = await callIdentify(imageId);
// In development without a real model, demo_mode should be true
expect(typeof data.demo_mode).toBe("boolean");
}, 30000);
it("each prediction has diseaseId, disease, confidence, and lookalikes", async () => {
const { data } = await callIdentify(imageId);
for (const pred of data.predictions) {
expect(pred.diseaseId).toBeDefined();
expect(typeof pred.diseaseId).toBe("string");
expect(pred.disease).toBeDefined();
expect(pred.disease.name).toBeDefined();
expect(pred.disease.description).toBeDefined();
expect(pred.disease.symptoms).toBeDefined();
expect(pred.disease.treatment).toBeDefined();
expect(pred.disease.prevention).toBeDefined();
expect(pred.confidence).toBeDefined();
expect(pred.confidence.raw).toBeDefined();
expect(pred.confidence.adjusted).toBeDefined();
expect(pred.confidence.label).toMatch(/^(high|medium|low)$/);
expect(pred.lookalikes).toBeDefined();
expect(Array.isArray(pred.lookalikes)).toBe(true);
}
}, 30000);
it("each prediction's diseaseId exists in knowledge base", async () => {
const { data } = await callIdentify(imageId);
for (const pred of data.predictions) {
const disease = await getDiseaseById(pred.diseaseId);
expect(disease).toBeDefined();
expect(disease!.id).toBe(pred.diseaseId);
expect(disease!.name).toBe(pred.disease.name);
}
}, 30000);
it("predictions are sorted by confidence descending", async () => {
const { data } = await callIdentify(imageId);
for (let i = 0; i < data.predictions.length - 1; i++) {
expect(data.predictions[i].confidence.adjusted).toBeGreaterThanOrEqual(
data.predictions[i + 1].confidence.adjusted,
);
}
}, 30000);
it("lookalike references are valid disease IDs", async () => {
const { data } = await callIdentify(imageId);
for (const pred of data.predictions) {
for (const lookalikeId of pred.lookalikes) {
const lookalike = await getDiseaseById(lookalikeId);
expect(lookalike).toBeDefined();
}
}
}, 30000);
it("inference completes under 3 seconds", async () => {
const start = performance.now();
const { data } = await callIdentify(imageId);
const elapsed = performance.now() - start;
expect(data.metadata.inferenceTimeMs).toBeLessThan(3000);
expect(elapsed).toBeLessThan(3000);
}, 10000);
it("confidence scores are in valid range", async () => {
const { data } = await callIdentify(imageId);
for (const pred of data.predictions) {
expect(pred.confidence.raw).toBeGreaterThanOrEqual(0);
expect(pred.confidence.raw).toBeLessThanOrEqual(1);
expect(pred.confidence.adjusted).toBeGreaterThanOrEqual(0);
expect(pred.confidence.adjusted).toBeLessThanOrEqual(1);
}
}, 30000);
it("disease entries have required fields", async () => {
const { data } = await callIdentify(imageId);
for (const pred of data.predictions) {
const disease = pred.disease;
expect(disease.id).toBeDefined();
expect(disease.plantId).toBeDefined();
expect(disease.name).toBeDefined();
expect(disease.scientificName).toBeDefined();
expect(disease.causalAgentType).toMatch(/^(fungal|bacterial|viral|environmental)$/);
expect(disease.description).toBeDefined();
expect(disease.symptoms.length).toBeGreaterThanOrEqual(3);
expect(disease.causes.length).toBeGreaterThanOrEqual(2);
expect(disease.treatment.length).toBeGreaterThanOrEqual(3);
expect(disease.prevention.length).toBeGreaterThanOrEqual(2);
expect(disease.severity).toMatch(/^(low|moderate|high|critical)$/);
}
}, 30000);
});

View File

@@ -0,0 +1,268 @@
/**
* Plant disease identification endpoint.
*
* Accepts POST with { imageId } from a previous /api/upload call.
* Loads the uploaded image, preprocesses it (resize + normalize),
* runs ML inference, enriches results with the knowledge base,
* and returns ranked predictions with confidence scores.
*
* When no model is available, returns deterministic mock predictions
* with demo_mode: true so the UI still works for development.
*/
import { NextRequest, NextResponse } from "next/server";
import path from "path";
import fs from "fs/promises";
import fsSync from "fs";
import { runInference } from "@/lib/ml/inference";
import { calibrateConfidence } from "@/lib/ml/confidence";
import { getDiseaseIdForIndex } from "@/lib/ml/labels";
import { getModel } from "@/lib/ml/model-loader";
import { getDiseaseById, getPlantById, getLookalikeDiseases } from "@/lib/api/diseases-db";
import type { IdentifyRequest, IdentifyResponse, PredictionResult } from "@/lib/types";
// ─── Constants ───────────────────────────────────────────────────────────────
const UPLOADS_DIR = path.join(process.cwd(), "public", "uploads");
/** ImageNet normalization constants */
const IMAGENET_MEAN = [0.485, 0.456, 0.406] as const;
const IMAGENET_STD = [0.229, 0.224, 0.225] as const;
/** Model input size */
const MODEL_SIZE = 160;
// ─── Server-side image preprocessing ─────────────────────────────────────────
/**
* Load an uploaded image and preprocess it into a Float32Array tensor
* with shape [3, 160, 160] (NCHW without batch dim) using ImageNet normalization.
*
* @param imageId - The image ID from the upload endpoint
* @returns Float32Array tensor ready for inference
* @throws Error if image not found
*/
async function loadImageAndPreprocess(imageId: string): Promise<Float32Array> {
// Find the image file — try original first, then resized version
const uploads = await fs.readdir(UPLOADS_DIR).catch(() => []);
// Find files matching this imageId
const matchingFiles = uploads.filter((f) => f.startsWith(imageId) && !f.includes("-resized"));
if (matchingFiles.length === 0) {
// Try the resized version
const resizedFile = `${imageId}-resized.jpg`;
if (fsSync.existsSync(path.join(UPLOADS_DIR, resizedFile))) {
return preprocessImageBuffer(await fs.readFile(path.join(UPLOADS_DIR, resizedFile)));
}
throw new Error(`Image not found: ${imageId}`);
}
const filename = matchingFiles[0];
const filePath = path.join(UPLOADS_DIR, filename);
const buffer = await fs.readFile(filePath);
return preprocessImageBuffer(buffer);
}
/**
* Preprocess an image buffer into a normalized Float32Array tensor.
* Uses sharp to resize, then applies ImageNet normalization.
*
* Output: flat Float32Array of length 3 × 224 × 224 in channel-first order
* (all R values, then all G values, then all B values).
*
* @param buffer - Raw image buffer
* @returns Normalized Float32Array tensor
*/
async function preprocessImageBuffer(buffer: Buffer): Promise<Float32Array> {
const sharpMod = await import("sharp");
const sharp = sharpMod.default;
// Resize to model input size and get raw pixel data
const pipeline = sharp(buffer).resize(MODEL_SIZE, MODEL_SIZE).raw().ensureAlpha(0); // RGB only, no alpha
const rawBuffer = await pipeline.toBuffer();
// Convert to Float32Array with channel-first layout and ImageNet normalization
const totalPixels = MODEL_SIZE * MODEL_SIZE;
const tensor = new Float32Array(3 * totalPixels);
// Extract channels from raw RGB data
const rChannel = tensor.subarray(0, totalPixels);
const gChannel = tensor.subarray(totalPixels, 2 * totalPixels);
const bChannel = tensor.subarray(2 * totalPixels, 3 * totalPixels);
for (let i = 0; i < totalPixels; i++) {
const idx = i * 3; // RGB stride
rChannel[i] = rawBuffer[idx] / 255;
gChannel[i] = rawBuffer[idx + 1] / 255;
bChannel[i] = rawBuffer[idx + 2] / 255;
}
// Apply ImageNet normalization
for (let c = 0; c < 3; c++) {
const channel = c === 0 ? rChannel : c === 1 ? gChannel : bChannel;
const m = IMAGENET_MEAN[c];
const s = IMAGENET_STD[c];
for (let i = 0; i < totalPixels; i++) {
channel[i] = (channel[i] - m) / s;
}
}
return tensor;
}
// ─── Result enrichment ───────────────────────────────────────────────────────
/**
* Enrich raw predictions with knowledge base data.
*
* For each prediction:
* - Look up disease by ID in knowledge base
* - Calibrate confidence score
* - Include lookalike disease cross-references (IDs and full objects)
*
* @param topPredictions - Top-K raw predictions from inference
* @returns Enriched prediction results
*/
async function enrichPredictions(
topPredictions: Array<{ classIndex: number; probability: number }>,
): Promise<PredictionResult[]> {
const results: PredictionResult[] = [];
for (const pred of topPredictions) {
const diseaseId = getDiseaseIdForIndex(pred.classIndex);
// Skip "healthy" and "unknown" — only return actual diseases
if (diseaseId === "healthy" || diseaseId === "unknown") {
continue;
}
// Look up disease in knowledge base
const disease = await getDiseaseById(diseaseId);
if (!disease) {
// Disease ID from model doesn't exist in knowledge base — skip
continue;
}
// Calibrate confidence
const confidence = calibrateConfidence(pred.probability);
// Pre-resolve lookalike disease objects server-side so the client
// doesn't need sync access to JSON files
const lookalikes = disease.lookalikeDiseaseIds;
const lookalikeDiseases = await getLookalikeDiseases(diseaseId);
// Look up the plant for client convenience
const plant = await getPlantById(disease.plantId).catch(() => null);
results.push({
diseaseId,
disease,
confidence,
lookalikes,
lookalikeDiseases,
plant: plant ?? null,
});
}
// Sort by adjusted confidence descending
results.sort((a, b) => b.confidence.adjusted - a.confidence.adjusted);
return results;
}
// ─── Route Handler ───────────────────────────────────────────────────────────
export async function POST(request: NextRequest) {
try {
// Parse request body
let body: IdentifyRequest;
try {
body = await request.json();
} catch {
return NextResponse.json(
{ error: "Invalid JSON", message: "Request body must be valid JSON.", status: 400 },
{ status: 400 },
);
}
const { imageId } = body;
// Validate imageId
if (!imageId || typeof imageId !== "string") {
return NextResponse.json(
{
error: "Missing imageId",
message: 'Request body must include "imageId" string.',
status: 400,
},
{ status: 400 },
);
}
// Check image exists
const uploads = await fs.readdir(UPLOADS_DIR).catch(() => []);
const imageExists = uploads.some((f) => f.startsWith(imageId));
if (!imageExists) {
return NextResponse.json(
{ error: "Image not found", message: `No image found with ID: ${imageId}`, status: 404 },
{ status: 404 },
);
}
// Load and preprocess image
const tensor = await loadImageAndPreprocess(imageId);
// Run inference
const { predictions: rawPredictions, inferenceTimeMs } = await runInference(tensor, 10);
// Get model status to check if we're in demo mode
const model = await getModel();
const modelStatus = model.getStatus();
const demoMode = !modelStatus.loaded;
// Calibrate and filter predictions
const calibratedPredictions = rawPredictions.map((pred) => ({
classIndex: pred.classIndex,
probability: pred.probability,
}));
// Enrich with knowledge base
const enrichedPredictions = await enrichPredictions(calibratedPredictions);
// Build response
const response: IdentifyResponse = {
predictions: enrichedPredictions,
metadata: {
model: modelStatus.modelId,
inferenceTimeMs,
imageId,
},
};
if (demoMode) {
response.demo_mode = true;
}
return NextResponse.json(response, {
headers: {
"Cache-Control": "no-store",
},
});
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
const status = message.includes("not found") ? 404 : 500;
console.error(`[identify] Error: ${message}`);
return NextResponse.json(
{
error: status === 404 ? "Image not found" : "Identification failed",
message,
status,
},
{ status },
);
}
}

View File

@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from "next/server";
import { getPlantWithDiseases } from "@/lib/api/diseases-db";
interface RouteParams {
params: Promise<{ id: string }>;
}
/**
* GET /api/plants/[id]
* Get a single plant with all its associated diseases.
*/
export async function GET(_request: NextRequest, { params }: RouteParams): Promise<NextResponse> {
const { id } = await params;
console.log(`[API] GET /api/plants/${id}`);
const result = await getPlantWithDiseases(id);
if (!result) {
return NextResponse.json(
{
error: "Not Found",
message: `Plant with ID "${id}" not found`,
status: 404,
},
{ status: 404, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
return NextResponse.json(result, {
headers: { "Cache-Control": "public, max-age=3600" },
});
}

View File

@@ -0,0 +1,38 @@
/**
* POST /api/plants/[id]/view
*
* Increments the view count for a plant in the plant_views table.
* Called client-side from the plant detail page via a tiny tracker component.
*/
import { NextResponse } from "next/server";
import { eq, sql } from "drizzle-orm";
import { getDb } from "@/lib/db/index";
import { plantViews } from "@/lib/db/schema";
export async function POST(_request: Request, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params;
if (!id) {
return NextResponse.json({ error: "Missing plant id" }, { status: 400 });
}
try {
const db = getDb();
// Upsert: increment view_count if row exists, otherwise insert with count 1
await db
.insert(plantViews)
.values({ plantId: id, viewCount: 1 })
.onConflictDoUpdate({
target: plantViews.plantId,
set: { viewCount: sql`${plantViews.viewCount} + 1` },
});
return NextResponse.json({ ok: true });
} catch (err) {
console.error("[View] Failed to record view for", id, err);
// Swallow errors — tracking failure shouldn't break the page
return NextResponse.json({ ok: true });
}
}

View File

@@ -0,0 +1,98 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { GET } from "./route";
import * as diseasesLib from "@/lib/api/diseases-db";
// Mock the diseases library
vi.mock("@/lib/api/diseases-db", () => ({
listPlants: vi.fn(() => Promise.resolve([])),
}));
describe("GET /api/plants", () => {
const createRequest = (searchParams: string) => {
const url = new URL(`http://localhost/api/plants${searchParams}`);
const req = new Request(url);
(req as any).nextUrl = url;
return req;
};
beforeEach(() => {
vi.clearAllMocks();
});
it("returns all plants with no filters", async () => {
(diseasesLib.listPlants as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "tomato", commonName: "Tomato" },
{ id: "pepper", commonName: "Pepper" },
]);
const response = await GET(createRequest(""));
expect(response.status).toBe(200);
const body = await response.json();
expect(body.plants).toHaveLength(2);
expect(body.total).toBe(2);
});
it("filters plants by search term", async () => {
(diseasesLib.listPlants as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "tomato", commonName: "Tomato" },
]);
const response = await GET(createRequest("?search=tomato"));
expect(response.status).toBe(200);
const body = await response.json();
expect(body.plants[0].commonName).toBe("Tomato");
});
it("filters plants by category", async () => {
(diseasesLib.listPlants as ReturnType<typeof vi.fn>).mockResolvedValue([
{ id: "tomato", commonName: "Tomato", category: "vegetable" },
]);
const response = await GET(createRequest("?category=vegetable"));
expect(response.status).toBe(200);
});
it("returns 400 for empty search term", async () => {
const response = await GET(createRequest("?search="));
expect(response.status).toBe(400);
const body = await response.json();
expect(body.error).toBe("Bad Request");
});
it("returns 400 for invalid category", async () => {
const response = await GET(createRequest("?category=invalid"));
expect(response.status).toBe(400);
const body = await response.json();
expect(body.message).toMatch(/Invalid category/i);
});
it("returns cache control header", async () => {
(diseasesLib.listPlants as ReturnType<typeof vi.fn>).mockResolvedValue([]);
const response = await GET(createRequest(""));
const cacheControl = response.headers.get("Cache-Control");
expect(cacheControl).toContain("max-age=3600");
});
it("accepts valid categories", async () => {
const validCategories = [
"vegetable",
"herb",
"houseplant",
"flower",
"fruit",
"succulent",
"tree",
];
(diseasesLib.listPlants as ReturnType<typeof vi.fn>).mockResolvedValue([]);
for (const cat of validCategories) {
const response = await GET(createRequest(`?category=${cat}`));
expect(response.status).toBe(200);
}
});
});

View File

@@ -0,0 +1,63 @@
import { NextRequest, NextResponse } from "next/server";
import { listPlants } from "@/lib/api/diseases-db";
/**
* GET /api/plants
* List all plants or search by term.
* Query params: ?search=<term> & ?category=<category>
*/
export async function GET(request: NextRequest) {
const { searchParams } = request.nextUrl;
const search = searchParams.get("search");
const category = searchParams.get("category") as
| "vegetable"
| "herb"
| "houseplant"
| "flower"
| "fruit"
| "succulent"
| "tree"
| null;
// Validate search param
if (search !== null && search.trim().length === 0) {
return NextResponse.json(
{ error: "Bad Request", message: "Search term cannot be empty", status: 400 },
{ status: 400, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
// Validate category param
const validCategories = [
"vegetable",
"herb",
"houseplant",
"flower",
"fruit",
"succulent",
"tree",
];
if (category !== null && !validCategories.includes(category)) {
return NextResponse.json(
{
error: "Bad Request",
message: `Invalid category. Must be one of: ${validCategories.join(", ")}`,
status: 400,
},
{ status: 400, headers: { "Cache-Control": "public, max-age=3600" } },
);
}
console.log(`[API] GET /api/plants search="${search}" category="${category}"`);
const results = await listPlants({
search: search || undefined,
category: category || undefined,
});
return NextResponse.json(
{ plants: results, total: results.length },
{ headers: { "Cache-Control": "public, max-age=3600" } },
);
}

View File

@@ -0,0 +1,98 @@
/**
* GET /api/plants/suggestions?q=<term>
*
* Returns autocomplete suggestions for the navbar search-as-you-type feature.
* Queries both plants and diseases from the database and returns an interleaved
* list with at most 8 suggestions total.
*
* Each suggestion includes: type (plant|disease), id, label, subtitle, emoji, href.
* Plants link to their browse detail page; diseases link to the plant page with
* a hash anchor to the specific disease card.
*/
import { NextRequest, NextResponse } from "next/server";
import { like, or, eq } from "drizzle-orm";
import { getDb } from "@/lib/db/index";
import { plants, diseases } from "@/lib/db/schema";
import { getEmojiForCategory } from "@/lib/display-helpers";
export const dynamic = "force-dynamic";
interface SuggestionItem {
type: "plant" | "disease";
id: string;
label: string;
subtitle: string;
emoji: string;
href: string;
}
export async function GET(request: NextRequest) {
const q = request.nextUrl.searchParams.get("q")?.trim() ?? "";
// Empty or very short queries return no suggestions
if (q.length < 1) {
return NextResponse.json({ suggestions: [] });
}
const db = getDb();
const term = `%${q.toLowerCase()}%`;
// Fetch matching plants (by common name or scientific name)
const plantRows = await db
.select({
id: plants.id,
commonName: plants.commonName,
scientificName: plants.scientificName,
category: plants.category,
})
.from(plants)
.where(or(like(plants.commonName, term), like(plants.scientificName, term)))
.limit(5);
// Fetch matching diseases (by name or scientific name) with parent plant info
const diseaseRows = await db
.select({
id: diseases.id,
name: diseases.name,
plantId: diseases.plantId,
plantCommonName: plants.commonName,
plantCategory: plants.category,
})
.from(diseases)
.leftJoin(plants, eq(diseases.plantId, plants.id))
.where(or(like(diseases.name, term), like(diseases.scientificName, term)))
.limit(5);
const plantSuggestions: SuggestionItem[] = plantRows.map((p) => ({
type: "plant" as const,
id: p.id,
label: p.commonName,
subtitle: p.scientificName,
emoji: getEmojiForCategory(p.category),
href: `/browse/${p.id}`,
}));
const diseaseSuggestions: SuggestionItem[] = diseaseRows.map((d) => ({
type: "disease" as const,
id: d.id,
label: d.name,
subtitle: `Disease on ${d.plantCommonName ?? "Unknown plant"}`,
emoji: getEmojiForCategory(d.plantCategory ?? "houseplant"),
href: `/browse/${d.plantId}#disease-${d.id}`,
}));
// Interleave plant and disease results so the dropdown shows variety
const interleaved: SuggestionItem[] = [];
const maxLen = Math.max(plantSuggestions.length, diseaseSuggestions.length);
for (let i = 0; i < maxLen && interleaved.length < 8; i++) {
if (i < plantSuggestions.length) {
interleaved.push(plantSuggestions[i]);
}
if (i < diseaseSuggestions.length && interleaved.length < 8) {
interleaved.push(diseaseSuggestions[i]);
}
}
return NextResponse.json({ suggestions: interleaved });
}

188
src/app/api/upload/route.ts Normal file
View File

@@ -0,0 +1,188 @@
/**
* Server-side image upload endpoint.
*
* Accepts multipart/form-data with field "image".
* Validates MIME type, file size, and minimum dimensions.
* Saves to public/uploads/{uuid}.{ext}.
* Runs server-side preprocessing (resize + normalize).
* Returns { imageId, tensorShape, previewUrl }.
*
* Cleanup: keeps last MAX_UPLOADS files, purges older ones.
*/
import { NextRequest, NextResponse } from "next/server";
import { v4 as uuidv4 } from "uuid";
import {
ALLOWED_MIME_TYPES,
MAX_FILE_SIZE,
MIN_DIMENSION,
MAX_UPLOADS,
getTensorShape,
} from "@/lib/image-processing";
import {
mimeTypeToExtension,
resizeImageServer,
} from "@/lib/server/image-processing-server";
import path from "path";
import fs from "fs/promises";
import fsSync from "fs";
// Uploads directory
const UPLOADS_DIR = path.join(process.cwd(), "public", "uploads");
// Ensure uploads directory exists
async function ensureUploadsDir(): Promise<void> {
await fs.mkdir(UPLOADS_DIR, { recursive: true });
}
/**
* List existing uploads sorted by modification time (oldest first).
*/
async function listUploads(): Promise<string[]> {
try {
const entries = await fs.readdir(UPLOADS_DIR);
const files = await Promise.all(
entries.map(async (name) => {
const stat = await fs.stat(path.join(UPLOADS_DIR, name));
return { name, mtime: stat.mtimeMs };
}),
);
return files.sort((a, b) => a.mtime - b.mtime).map((f) => f.name);
} catch {
return [];
}
}
/**
* Purge oldest uploads to stay within MAX_UPLOADS limit.
*/
async function cleanupOldUploads(): Promise<void> {
const files = await listUploads();
const toDelete = files.slice(0, files.length - MAX_UPLOADS);
await Promise.all(
toDelete.map((name) =>
fs.unlink(path.join(UPLOADS_DIR, name)).catch(() => {}),
),
);
}
/**
* Read image dimensions from a buffer without full decode.
* Uses sharp to get metadata efficiently.
*/
async function getImageDimensions(buffer: Buffer): Promise<{
width: number;
height: number;
}> {
try {
const sharpMod = await import("sharp");
const sharp = sharpMod.default;
const metadata = await sharp(buffer).metadata();
return {
width: metadata.width ?? 0,
height: metadata.height ?? 0,
};
} catch {
throw new Error("sharp is required for image dimension validation.");
}
}
// ─── Route Handler ───────────────────────────────────────────────────────────
export async function POST(request: NextRequest) {
try {
await ensureUploadsDir();
// Parse multipart form data
const formData = await request.formData();
const imageFile = formData.get("image");
if (!imageFile || !(imageFile instanceof File)) {
return NextResponse.json(
{ error: "Missing file", message: 'No "image" field in form data.', status: 400 },
{ status: 400 },
);
}
// Validate MIME type
const mimeType = imageFile.type;
if (!ALLOWED_MIME_TYPES.includes(mimeType as (typeof ALLOWED_MIME_TYPES)[number])) {
return NextResponse.json(
{
error: "Invalid MIME type",
message: `Type "${mimeType}" not allowed. Allowed: ${ALLOWED_MIME_TYPES.join(", ")}.`,
status: 400,
},
{ status: 400 },
);
}
// Validate file size
if (imageFile.size > MAX_FILE_SIZE) {
const mb = (imageFile.size / (1024 * 1024)).toFixed(1);
return NextResponse.json(
{
error: "File too large",
message: `File is ${mb} MB. Maximum is 10 MB.`,
status: 413,
},
{ status: 413 },
);
}
// Read file buffer
const buffer = Buffer.from(await imageFile.arrayBuffer());
// Validate dimensions
const { width, height } = await getImageDimensions(buffer);
if (width < MIN_DIMENSION || height < MIN_DIMENSION) {
return NextResponse.json(
{
error: "Image too small",
message: `Image is ${width}×${height}. Minimum is ${MIN_DIMENSION}×${MIN_DIMENSION}.`,
status: 400,
},
{ status: 400 },
);
}
// Generate unique filename
const imageId = uuidv4();
const ext = mimeTypeToExtension(mimeType);
const filename = `${imageId}.${ext}`;
const filePath = path.join(UPLOADS_DIR, filename);
// Save original file
await fs.writeFile(filePath, buffer);
// Server-side preprocessing: resize to model size
const modelSize = 224;
const resizedBuffer = await resizeImageServer(buffer, modelSize);
// Save resized version (for preview / model input)
const resizedFilename = `${imageId}-resized.jpg`;
const resizedPath = path.join(UPLOADS_DIR, resizedFilename);
await fs.writeFile(resizedPath, resizedBuffer);
// Cleanup old uploads
await cleanupOldUploads();
// Return response
return NextResponse.json({
imageId,
tensorShape: getTensorShape(),
previewUrl: `/uploads/${filename}`,
});
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
console.error("[upload] Error:", message);
return NextResponse.json(
{
error: "Upload failed",
message,
status: 500,
},
{ status: 500 },
);
}
}

View File

@@ -0,0 +1,141 @@
/**
* Integration tests for app/api/upload/route.ts
*
* These tests call the actual running dev server via fetch.
* Run with: `npm run dev` in one terminal, then `npx vitest run src/app/api/upload/upload.test.ts`
*
* Tests:
* - Upload a valid JPG → POST /api/upload returns 200 with expected shape
* - Upload a 12 MB file → returns 413 or validation error
* - Upload a .txt file → returns 400 with MIME error
* - Upload missing field → returns 400
* - Upload too-small image → returns 400
*/
// @vitest-environment node
import { describe, it, expect, beforeAll } from "vitest";
const BASE_URL = process.env.TEST_BASE_URL || "http://localhost:3000";
// ─── Helpers ─────────────────────────────────────────────────────────────────
/**
* Create a test image buffer using sharp.
*/
async function createTestImage(
width: number,
height: number,
bg = { r: 34, g: 197, b: 94 },
): Promise<Buffer> {
const sharpMod = await import("sharp");
const sharp = sharpMod.default;
return sharp({
create: { width, height, channels: 3, background: bg },
})
.jpeg({ quality: 90 })
.toBuffer();
}
/**
* Upload a file to the /api/upload endpoint and return the response.
*/
async function uploadFile(file: File): Promise<{
status: number;
data: any;
ok: boolean;
}> {
const formData = new FormData();
formData.append("image", file);
const response = await fetch(`${BASE_URL}/api/upload`, {
method: "POST",
body: formData,
});
const data = await response.json();
return { status: response.status, data, ok: response.ok };
}
// ─── Tests ───────────────────────────────────────────────────────────────────
describe("POST /api/upload", () => {
beforeAll(() => {
// Ensure the dev server is running
if (!BASE_URL) {
console.warn(
"TEST_BASE_URL not set. Using default http://localhost:3000",
);
}
});
it("accepts a valid JPEG and returns imageId, tensorShape, previewUrl", async () => {
const buffer = await createTestImage(300, 300);
const file = new File([buffer], "test.jpg", { type: "image/jpeg" });
const { status, data } = await uploadFile(file);
expect(status).toBe(200);
expect(data.imageId).toBeDefined();
expect(typeof data.imageId).toBe("string");
expect(data.imageId.length).toBeGreaterThan(0);
expect(data.tensorShape).toEqual([1, 3, 224, 224]);
expect(data.previewUrl).toMatch(/^\/uploads\/.*\.jpg$/);
}, 15000);
it("accepts a valid PNG", async () => {
const buffer = await createTestImage(200, 200);
const file = new File([buffer], "test.png", { type: "image/png" });
const { status, data } = await uploadFile(file);
expect(status).toBe(200);
expect(data.previewUrl).toMatch(/^\/uploads\/.*\.png$/);
}, 15000);
it("accepts a valid WebP", async () => {
const buffer = await createTestImage(200, 200);
const file = new File([buffer], "test.webp", { type: "image/webp" });
const { status } = await uploadFile(file);
expect(status).toBe(200);
}, 15000);
it("rejects a .txt file with 400 MIME error", async () => {
const file = new File(["not an image"], "document.txt", {
type: "text/plain",
});
const { status, data } = await uploadFile(file);
expect(status).toBe(400);
expect(data.error).toBe("Invalid MIME type");
expect(data.message).toContain("text/plain");
}, 15000);
it("rejects a file >10 MB with 413", async () => {
const bigBuffer = Buffer.alloc(12 * 1024 * 1024);
const file = new File([bigBuffer], "huge.jpg", { type: "image/jpeg" });
const { status, data } = await uploadFile(file);
expect(status).toBe(413);
expect(data.error).toBe("File too large");
}, 30000);
it("rejects an image that is too small (<150×150)", async () => {
const buffer = await createTestImage(50, 50);
const file = new File([buffer], "tiny.jpg", { type: "image/jpeg" });
const { status, data } = await uploadFile(file);
expect(status).toBe(400);
expect(data.error).toBe("Image too small");
expect(data.message).toContain("150");
}, 15000);
it("returns tensorShape [1, 3, 224, 224] for any valid input", async () => {
// Test with a non-square image
const buffer = await createTestImage(400, 200);
const file = new File([buffer], "wide.jpg", { type: "image/jpeg" });
const { status, data } = await uploadFile(file);
expect(status).toBe(200);
expect(data.tensorShape).toEqual([1, 3, 224, 224]);
}, 15000);
});

View File

@@ -0,0 +1,209 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen, fireEvent } from "@testing-library/react";
import BrowseContent from "@/app/browse/BrowseContent";
import type { PlantCardData } from "@/components/PlantCard";
// Mock Next.js navigation
vi.mock("next/navigation", () => ({
useSearchParams: vi.fn(() => ({
get: vi.fn(() => null),
})),
}));
// Mock PlantCard
vi.mock("@/components/PlantCard", () => ({
default: ({ plant }: { plant: PlantCardData }) => (
<div data-testid={`plant-card-${plant.id}`}>
<span>{plant.commonName}</span>
</div>
),
}));
// Mock EmptyState
vi.mock("@/components/EmptyState", () => ({
default: ({ title, description, actionLabel }: any) => (
<div data-testid="empty-state">
<span data-testid="empty-title">{title}</span>
<span data-testid="empty-desc">{description}</span>
{actionLabel && <span>{actionLabel}</span>}
</div>
),
}));
const MOCK_PLANTS: PlantCardData[] = [
{
id: "tomato",
commonName: "Tomato",
scientificName: "Solanum lycopersicum",
family: "Solanaceae",
category: "vegetable",
imageUrl: "https://example.com/tomato.jpg",
diseaseCount: 15,
},
{
id: "basil",
commonName: "Basil",
scientificName: "Ocimum basilicum",
family: "Lamiaceae",
category: "herb",
imageUrl: "https://example.com/basil.jpg",
diseaseCount: 3,
},
{
id: "rose",
commonName: "Rose",
scientificName: "Rosa spp.",
family: "Rosaceae",
category: "flower",
imageUrl: "https://example.com/rose.jpg",
diseaseCount: 7,
},
{
id: "monstera",
commonName: "Monstera",
scientificName: "Monstera deliciosa",
family: "Araceae",
category: "houseplant",
imageUrl: "https://example.com/monstera.jpg",
diseaseCount: 5,
},
{
id: "snake-plant",
commonName: "Snake Plant",
scientificName: "Dracaena trifasciata",
family: "Asparagaceae",
category: "houseplant",
imageUrl: "https://example.com/snake-plant.jpg",
diseaseCount: 2,
},
{
id: "pepper",
commonName: "Bell Pepper",
scientificName: "Capsicum annuum",
family: "Solanaceae",
category: "vegetable",
imageUrl: "https://example.com/pepper.jpg",
diseaseCount: 9,
},
];
describe("BrowseContent", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("renders page header with plant count", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
expect(screen.getByText("Browse Plants")).toBeInTheDocument();
});
it("renders search input", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox", {
name: /Search plants and diseases/i,
});
expect(searchInput).toBeInTheDocument();
});
it("filters plants by search query", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox") as HTMLInputElement;
fireEvent.change(searchInput, { target: { value: "tomato" } });
// Should show tomato plant
expect(screen.getByText("Tomato")).toBeInTheDocument();
});
it("shows results count", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
expect(screen.getByText(/Showing \d+ plants/i)).toBeInTheDocument();
});
it("renders category filter tabs", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const tablist = screen.getByRole("tablist", { name: /Plant categories/i });
expect(tablist).toBeInTheDocument();
// Should have category tabs
const tabs = screen.getAllByRole("tab");
expect(tabs.length).toBeGreaterThan(0);
});
it("filters by category when tab is clicked", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const tabs = screen.getAllByRole("tab");
// Click a category tab (not 'all')
const vegTab = tabs.find((t) => t.textContent?.toLowerCase().includes("vegetable"));
if (vegTab) {
fireEvent.click(vegTab);
expect(screen.getByText(/in vegetable/i)).toBeInTheDocument();
}
});
it("clears search when clear button is clicked", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox") as HTMLInputElement;
fireEvent.change(searchInput, { target: { value: "tomato" } });
expect(searchInput.value).toBe("tomato");
const clearBtn = screen.getByRole("button", { name: /Clear search/i });
fireEvent.click(clearBtn);
expect(searchInput.value).toBe("");
});
it("shows empty state when no plants match search", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox") as HTMLInputElement;
fireEvent.change(searchInput, { target: { value: "xyznonexistent123" } });
expect(screen.getByTestId("empty-title")).toHaveTextContent("No plants found");
});
it("shows empty state with search query in description", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox") as HTMLInputElement;
fireEvent.change(searchInput, { target: { value: "xyznonexistent123" } });
expect(screen.getByTestId("empty-desc")).toHaveTextContent(/xyznonexistent123/i);
});
it("shows matching text in results count", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox") as HTMLInputElement;
fireEvent.change(searchInput, { target: { value: "tomato" } });
expect(screen.getByText(/matching "tomato"/i)).toBeInTheDocument();
});
it("renders all plant cards when no filter applied", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
// Should show all plants
const plantCards = screen.getAllByTestId(/plant-card-/);
expect(plantCards.length).toBe(MOCK_PLANTS.length);
});
it("searches by scientific name", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox") as HTMLInputElement;
fireEvent.change(searchInput, { target: { value: "solanum" } });
expect(screen.getByText("Tomato")).toBeInTheDocument();
});
it("searches by family name", () => {
render(<BrowseContent allPlants={MOCK_PLANTS} />);
const searchInput = screen.getByRole("searchbox") as HTMLInputElement;
fireEvent.change(searchInput, { target: { value: "solanaceae" } });
expect(screen.getByText("Tomato")).toBeInTheDocument();
});
});

View File

@@ -0,0 +1,226 @@
"use client";
import React, { useState, useMemo } from "react";
import { useSearchParams } from "next/navigation";
import PlantCard from "@/components/PlantCard";
import EmptyState from "@/components/EmptyState";
import { PLANT_CATEGORIES } from "@/lib/constants";
import type { PlantCardData } from "@/components/PlantCard";
type SortKey = "name" | "recent" | "popular";
const SORT_OPTIONS: { value: SortKey; label: string }[] = [
{ value: "name", label: "Name (A-Z)" },
{ value: "recent", label: "Recently Updated" },
{ value: "popular", label: "Most Popular" },
];
interface BrowseContentProps {
allPlants: PlantCardData[];
}
type Category = string | "all";
/**
* Client component that handles the interactive browse/search/filter logic.
* Receives all plants as props from the parent server component.
* Wrapped in a Suspense boundary in the parent page.
*/
export default function BrowseContent({ allPlants }: BrowseContentProps) {
const searchParams = useSearchParams();
const initialSearch = searchParams.get("search") || "";
const [searchQuery, setSearchQuery] = useState(initialSearch);
const [activeCategory, setActiveCategory] = useState<Category>("all");
const [sortKey, setSortKey] = useState<SortKey>("name");
const filteredPlants = useMemo(() => {
let result = allPlants;
if (activeCategory !== "all") {
result = result.filter((p) => p.category === activeCategory);
}
const q = searchQuery.toLowerCase().trim();
if (q) {
result = result.filter(
(p) =>
p.commonName.toLowerCase().includes(q) ||
p.scientificName.toLowerCase().includes(q) ||
p.family.toLowerCase().includes(q),
);
}
// Sort
const sorted = [...result];
if (sortKey === "recent") {
sorted.sort((a, b) => {
const aTime = a.updatedAt ? new Date(a.updatedAt).getTime() : 0;
const bTime = b.updatedAt ? new Date(b.updatedAt).getTime() : 0;
return bTime - aTime; // newest first
});
} else if (sortKey === "popular") {
sorted.sort((a, b) => (b.viewCount ?? 0) - (a.viewCount ?? 0));
} else {
sorted.sort((a, b) => a.commonName.localeCompare(b.commonName));
}
return sorted;
}, [activeCategory, searchQuery, allPlants, sortKey]);
return (
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
{/* Page header */}
<div className="mb-8">
<h1 className="text-3xl font-bold text-zinc-900 dark:text-zinc-100">Browse Plants</h1>
<p className="mt-2 text-zinc-500 dark:text-zinc-400">
Explore our database of {allPlants.length} plants and their common diseases.
</p>
</div>
{/* Controls row: search + sort */}
<div className="flex flex-col sm:flex-row gap-3 mb-6">
{/* Search bar */}
<div className="relative flex-1">
<label htmlFor="browse-search" className="sr-only">
Search plants and diseases
</label>
<div className="relative">
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="absolute left-3.5 top-1/2 -translate-y-1/2 text-zinc-400"
aria-hidden="true"
>
<circle cx="11" cy="11" r="8" />
<path d="m21 21-4.3-4.3" />
</svg>
<input
id="browse-search"
type="search"
placeholder="Search by plant name, scientific name, or family..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full rounded-xl border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-900 pl-10 pr-4 py-3 text-sm text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:border-leaf-green-500 transition-all shadow-sm"
/>
</div>
{searchQuery && (
<button
type="button"
onClick={() => setSearchQuery("")}
className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400 hover:text-zinc-600 dark:hover:text-zinc-300 transition-colors"
aria-label="Clear search"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
>
<path d="M18 6 6 18" />
<path d="m6 6 12 12" />
</svg>
</button>
)}
</div>
{/* Sort dropdown */}
<div className="relative shrink-0">
<label htmlFor="sort-select" className="sr-only">
Sort by
</label>
<select
id="sort-select"
value={sortKey}
onChange={(e) => setSortKey(e.target.value as SortKey)}
className="w-full sm:w-auto appearance-none rounded-xl border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-900 px-4 py-3 pr-10 text-sm text-zinc-700 dark:text-zinc-300 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:border-leaf-green-500 transition-all shadow-sm cursor-pointer"
>
{SORT_OPTIONS.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
<svg
xmlns="http://www.w3.org/2000/svg"
width="16"
height="16"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
className="pointer-events-none absolute right-3 top-1/2 -translate-y-1/2 text-zinc-400"
aria-hidden="true"
>
<path d="m6 9 6 6 6-6" />
</svg>
</div>
</div>
{/* Category filter chips */}
<div className="flex flex-wrap gap-2 mb-8" role="tablist" aria-label="Plant categories">
{PLANT_CATEGORIES.map((cat) => (
<button
key={cat.value}
role="tab"
aria-selected={activeCategory === cat.value}
onClick={() => setActiveCategory(cat.value as Category)}
className={`px-4 py-2 text-sm font-medium rounded-full transition-all focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2 ${
activeCategory === cat.value
? "bg-leaf-green-600 text-white shadow-sm"
: "bg-zinc-100 dark:bg-zinc-800 text-zinc-600 dark:text-zinc-400 hover:bg-zinc-200 dark:hover:bg-zinc-700"
}`}
>
{cat.label}
</button>
))}
</div>
{/* Results count */}
<p className="text-sm text-zinc-500 dark:text-zinc-400 mb-6">
{filteredPlants.length === 0
? "No plants found"
: `Showing ${filteredPlants.length} ${filteredPlants.length === 1 ? "plant" : "plants"}`}
{activeCategory !== "all" &&
` in ${PLANT_CATEGORIES.find((c) => c.value === activeCategory)?.label.toLowerCase()}`}
{searchQuery.trim() && ` matching "${searchQuery.trim()}"`}
</p>
{/* Plant grid or empty state */}
{filteredPlants.length > 0 ? (
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6">
{filteredPlants.map((plant) => (
<PlantCard key={plant.id} plant={plant} />
))}
</div>
) : (
<EmptyState
illustration="🔍"
title="No plants found"
description={
searchQuery.trim()
? `We couldn't find any plants matching "${searchQuery.trim()}". Try a different search term or browse a different category.`
: "No plants in this category yet. We're constantly adding new plants to our database."
}
actionLabel="Clear filters"
actionHref="/browse"
/>
)}
</div>
);
}

View File

@@ -0,0 +1,524 @@
"use client";
import { useState, useCallback, useMemo } from "react";
import type { Disease, CausalAgentType, Prevalence, Severity } from "@/lib/types";
import ImageLightbox from "@/components/ImageLightbox";
import FlagButton from "@/components/FlagButton";
// ─── Severity badge ───
function SeverityBadge({ severity }: { severity: Severity }) {
const colors: Record<Severity, string> = {
low: "bg-leaf-green-100 text-leaf-green-800 dark:bg-leaf-green-900/40 dark:text-leaf-green-300",
moderate:
"bg-warning-amber-100 text-warning-amber-800 dark:bg-warning-amber-900/40 dark:text-warning-amber-300",
high: "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300",
critical: "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300",
};
const labels: Record<Severity, string> = {
low: "Low",
moderate: "Moderate",
high: "High",
critical: "Critical",
};
return (
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colors[severity]}`}
>
{severity === "critical" ? "🚨 " : ""}
{labels[severity]} Severity
</span>
);
}
// ─── Disease type badge ───
function TypeBadge({ type }: { type: CausalAgentType }) {
const colors: Record<CausalAgentType, string> = {
fungal: "bg-purple-100 text-purple-800 dark:bg-purple-900/40 dark:text-purple-300",
bacterial: "bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-300",
viral: "bg-pink-100 text-pink-800 dark:bg-pink-900/40 dark:text-pink-300",
environmental: "bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-300",
};
return (
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colors[type]}`}
>
{type === "environmental" ? "Environmental" : type.charAt(0).toUpperCase() + type.slice(1)}
</span>
);
}
// ─── Disease card ───
function DiseaseCard({
disease,
onImageClick,
}: {
disease: Disease;
onImageClick: (disease: Disease) => void;
}) {
return (
<div
id={`disease-${disease.id}`}
className="rounded-xl border border-zinc-200 dark:border-zinc-700 bg-white dark:bg-zinc-900 overflow-hidden shadow-sm hover:shadow-md transition-shadow"
>
{/* Card header */}
<div className="p-5 sm:p-6">
<div className="flex flex-wrap items-start justify-between gap-3 mb-3">
<div>
<h3 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
{disease.name}
</h3>
{disease.scientificName && (
<p className="text-sm text-zinc-500 dark:text-zinc-400 italic mt-0.5">
{disease.scientificName}
</p>
)}
</div>
<div className="flex flex-wrap gap-2">
<PrevalenceBadge prevalence={disease.prevalence} />
<TypeBadge type={disease.causalAgentType} />
<SeverityBadge severity={disease.severity} />
</div>
</div>
{/* Disease image or placeholder */}
<div className="mb-2 rounded-lg overflow-hidden border border-zinc-200 dark:border-zinc-700 relative">
{disease.imageUrl ? (
<button
type="button"
onClick={() => onImageClick(disease)}
className="block w-full cursor-pointer group"
aria-label={`View larger image of ${disease.name} symptoms`}
>
<img
src={disease.imageUrl}
alt={`${disease.name} symptoms`}
className="w-full h-48 sm:h-64 object-cover transition-all duration-200 group-hover:brightness-75 group-hover:scale-[1.02]"
loading="lazy"
/>
</button>
) : (
<div className="flex items-center justify-center h-36 sm:h-48 bg-gradient-to-br from-zinc-100 to-zinc-200 dark:from-zinc-800 dark:to-zinc-900">
<div className="text-center">
<span className="text-5xl block mb-2" aria-hidden="true">
{disease.causalAgentType === "fungal"
? "🍄"
: disease.causalAgentType === "bacterial"
? "🦠"
: disease.causalAgentType === "viral"
? "🧬"
: disease.causalAgentType === "environmental"
? "🌡️"
: "🔬"}
</span>
<p className="text-xs text-zinc-400 dark:text-zinc-500">
{disease.causalAgentType === "fungal"
? "Fungal pathogen"
: disease.causalAgentType === "bacterial"
? "Bacterial infection"
: disease.causalAgentType === "viral"
? "Viral infection"
: "Environmental disorder"}
</p>
</div>
</div>
)}
</div>
{/* Flag button for disease image */}
<div className="flex justify-end mb-2">
<FlagButton
contentType="disease_image"
contentId={disease.id}
fieldName="image"
label="disease image"
small
/>
</div>
<div className="flex items-start justify-between gap-4 mb-4">
<p className="text-sm text-zinc-600 dark:text-zinc-300 leading-relaxed">
{disease.description}
</p>
<FlagButton
contentType="disease_description"
contentId={disease.id}
fieldName="description"
label="description"
small
className="shrink-0 mt-0.5"
/>
</div>
{/* Details grid */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
{/* Symptoms */}
<div>
<div className="flex items-center justify-between mb-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-red-600 dark:text-red-400 flex items-center gap-1">
<span aria-hidden="true">⚠️</span> Symptoms
</h4>
<FlagButton
contentType="disease_symptoms"
contentId={disease.id}
fieldName="symptoms"
label="symptoms"
small
/>
</div>
<ul className="space-y-1.5">
{disease.symptoms.map((symptom, i) => (
<li
key={i}
className="flex items-start gap-2 text-sm text-zinc-600 dark:text-zinc-300"
>
<span className="mt-1 shrink-0 h-1.5 w-1.5 rounded-full bg-red-400 dark:bg-red-500" />
{symptom}
</li>
))}
</ul>
</div>
{/* Causes */}
<div>
<div className="flex items-center justify-between mb-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-orange-600 dark:text-orange-400 flex items-center gap-1">
<span aria-hidden="true">🔍</span> Causes
</h4>
<FlagButton
contentType="disease_causes"
contentId={disease.id}
fieldName="causes"
label="causes"
small
/>
</div>
<ul className="space-y-1.5">
{disease.causes.map((cause, i) => (
<li
key={i}
className="flex items-start gap-2 text-sm text-zinc-600 dark:text-zinc-300"
>
<span className="mt-1 shrink-0 h-1.5 w-1.5 rounded-full bg-orange-400 dark:bg-orange-500" />
{cause}
</li>
))}
</ul>
</div>
{/* Treatment Steps */}
<div>
<div className="flex items-center justify-between mb-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-leaf-green-600 dark:text-leaf-green-400 flex items-center gap-1">
<span aria-hidden="true">💊</span> Treatment Steps
</h4>
<FlagButton
contentType="disease_treatment"
contentId={disease.id}
fieldName="treatment"
label="treatment"
small
/>
</div>
<ol className="space-y-1.5 list-decimal list-inside">
{disease.treatment.map((step, i) => (
<li key={i} className="text-sm text-zinc-600 dark:text-zinc-300">
{step}
</li>
))}
</ol>
</div>
{/* Prevention Tips */}
<div>
<div className="flex items-center justify-between mb-2">
<h4 className="text-xs font-semibold uppercase tracking-wider text-leaf-green-600 dark:text-leaf-green-400 flex items-center gap-1">
<span aria-hidden="true">🛡️</span> Prevention Tips
</h4>
<FlagButton
contentType="disease_prevention"
contentId={disease.id}
fieldName="prevention"
label="prevention tips"
small
/>
</div>
<ul className="space-y-1.5">
{disease.prevention.map((tip, i) => (
<li
key={i}
className="flex items-start gap-2 text-sm text-zinc-600 dark:text-zinc-300"
>
<span className="mt-1 shrink-0 h-1.5 w-1.5 rounded-full bg-leaf-green-400 dark:bg-leaf-green-500" />
{tip}
</li>
))}
</ul>
</div>
</div>
</div>
</div>
);
}
// ─── Prevalence badge ───
function PrevalenceBadge({ prevalence }: { prevalence: Prevalence }) {
const icons: Record<Prevalence, string> = {
common: "📊",
uncommon: "📋",
rare: "📌",
very_rare: "🔍",
};
const colors: Record<Prevalence, string> = {
common: "bg-emerald-100 text-emerald-800 dark:bg-emerald-900/40 dark:text-emerald-300",
uncommon: "bg-zinc-100 text-zinc-700 dark:bg-zinc-800/60 dark:text-zinc-300",
rare: "bg-amber-100 text-amber-800 dark:bg-amber-900/40 dark:text-amber-300",
very_rare: "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-300",
};
const label = prevalence.replace(/_/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
return (
<span
className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${colors[prevalence]}`}
>
{icons[prevalence]} {label}
</span>
);
}
// ─── Sort / Search controls ───
const SEVERITY_RANK: Record<Severity, number> = {
critical: 4,
high: 3,
moderate: 2,
low: 1,
};
const PREVALENCE_RANK: Record<Prevalence, number> = {
common: 4,
uncommon: 3,
rare: 2,
very_rare: 1,
};
type SortField = "prevalence" | "danger";
function SearchSortBar({
searchQuery,
onSearchChange,
sortField,
onSortFieldChange,
sortOrder,
onSortOrderToggle,
resultCount,
}: {
searchQuery: string;
onSearchChange: (q: string) => void;
sortField: SortField;
onSortFieldChange: (f: SortField) => void;
sortOrder: "asc" | "desc";
onSortOrderToggle: () => void;
resultCount: number;
}) {
return (
<div className="mb-6 space-y-4">
{/* Search */}
<div className="relative">
<span
className="absolute inset-y-0 left-0 flex items-center pl-3 text-zinc-400 dark:text-zinc-500 pointer-events-none"
aria-hidden="true"
>
<svg
className="h-4 w-4"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="m21 21-4.35-4.35M11 19a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z"
/>
</svg>
</span>
<input
type="search"
value={searchQuery}
onChange={(e) => onSearchChange(e.target.value)}
placeholder="Search diseases by name…"
className="w-full rounded-lg border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-800 py-2 pl-10 pr-3 text-sm text-zinc-900 dark:text-zinc-100 placeholder-zinc-400 dark:placeholder-zinc-500 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:border-leaf-green-500 transition-colors"
aria-label="Search diseases"
/>
</div>
{/* Sort controls */}
<div className="flex flex-wrap items-center gap-3 text-sm">
<span className="text-zinc-500 dark:text-zinc-400 font-medium">Sort by:</span>
<div className="flex rounded-lg border border-zinc-300 dark:border-zinc-600 overflow-hidden">
<button
type="button"
onClick={() => onSortFieldChange("prevalence")}
className={`px-3 py-1.5 text-xs font-medium transition-colors ${
sortField === "prevalence"
? "bg-leaf-green-600 text-white"
: "bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700"
}`}
>
Prevalence
</button>
<button
type="button"
onClick={() => onSortFieldChange("danger")}
className={`px-3 py-1.5 text-xs font-medium transition-colors ${
sortField === "danger"
? "bg-leaf-green-600 text-white"
: "bg-white dark:bg-zinc-800 text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700"
}`}
>
Danger
</button>
</div>
{/* Direction toggle */}
<button
type="button"
onClick={onSortOrderToggle}
className="inline-flex items-center gap-1 rounded-lg border border-zinc-300 dark:border-zinc-600 bg-white dark:bg-zinc-800 px-3 py-1.5 text-xs font-medium text-zinc-600 dark:text-zinc-300 hover:bg-zinc-100 dark:hover:bg-zinc-700 transition-colors"
aria-label={
sortOrder === "desc"
? "Sorted descending, click for ascending"
: "Sorted ascending, click for descending"
}
>
<svg
className={`h-3.5 w-3.5 transition-transform ${sortOrder === "asc" ? "rotate-180" : ""}`}
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={2}
>
<path strokeLinecap="round" strokeLinejoin="round" d="M19 9l-7 7-7-7" />
</svg>
{sortField === "danger"
? sortOrder === "desc"
? "Most dangerous first"
: "Least dangerous first"
: sortOrder === "desc"
? "Most prevalent first"
: "Least prevalent first"}
</button>
<span className="text-xs text-zinc-400 dark:text-zinc-500 ml-auto">
{resultCount} {resultCount === 1 ? "result" : "results"}
</span>
</div>
</div>
);
}
// ─── Client component wrapper ───
export default function DiseaseCards({ diseases }: { diseases: Disease[] }) {
const [lightboxOpen, setLightboxOpen] = useState(false);
const [lightboxIndex, setLightboxIndex] = useState(0);
const [searchQuery, setSearchQuery] = useState("");
const [sortField, setSortField] = useState<SortField>("danger");
const [sortOrder, setSortOrder] = useState<"asc" | "desc">("desc");
// ── Filtered + sorted diseases ──
const processed = useMemo(() => {
// Filter
let result = diseases;
const trimmed = searchQuery.trim().toLowerCase();
if (trimmed) {
result = result.filter(
(d) =>
d.name.toLowerCase().includes(trimmed) ||
d.scientificName.toLowerCase().includes(trimmed),
);
}
// Sort
const sorted = [...result].sort((a, b) => {
let cmp: number;
if (sortField === "danger") {
cmp = SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity];
} else {
cmp = PREVALENCE_RANK[a.prevalence] - PREVALENCE_RANK[b.prevalence];
}
return sortOrder === "desc" ? -cmp : cmp;
});
return sorted;
}, [diseases, searchQuery, sortField, sortOrder]);
// Build list of images from processed diseases that have imageUrls
const images = useMemo(
() =>
processed
.filter((d) => d.imageUrl)
.map((d) => ({ src: d.imageUrl!, alt: `${d.name} symptoms` })),
[processed],
);
const handleImageClick = useCallback(
(disease: Disease) => {
const index = images.findIndex((img) => img.src === disease.imageUrl);
setLightboxIndex(index >= 0 ? index : 0);
setLightboxOpen(true);
},
[images],
);
const handleClose = useCallback(() => setLightboxOpen(false), []);
const handleSortOrderToggle = useCallback(() => {
setSortOrder((prev) => (prev === "desc" ? "asc" : "desc"));
}, []);
if (diseases.length === 0) return null;
return (
<>
<SearchSortBar
searchQuery={searchQuery}
onSearchChange={setSearchQuery}
sortField={sortField}
onSortFieldChange={setSortField}
sortOrder={sortOrder}
onSortOrderToggle={handleSortOrderToggle}
resultCount={processed.length}
/>
{processed.length > 0 ? (
<div className="space-y-6">
{processed.map((disease) => (
<DiseaseCard key={disease.id} disease={disease} onImageClick={handleImageClick} />
))}
</div>
) : (
<div className="rounded-xl border border-dashed border-zinc-300 dark:border-zinc-700 p-10 text-center">
<span className="text-4xl block mb-3" aria-hidden="true">
🔍
</span>
<p className="text-zinc-500 dark:text-zinc-400 text-sm">
No diseases match &ldquo;{searchQuery}&rdquo;.
</p>
</div>
)}
{lightboxOpen && images.length > 0 && (
<ImageLightbox images={images} initialIndex={lightboxIndex} onClose={handleClose} />
)}
</>
);
}

View File

@@ -0,0 +1,195 @@
import Image from "next/image";
import Link from "next/link";
import { notFound } from "next/navigation";
import type { Metadata } from "next";
import { getPlantWithDiseases } from "@/lib/api/diseases-db";
import { getPlantDescription } from "@/lib/display-helpers";
import BetaNotice from "@/components/BetaNotice";
import DiseaseCards from "./DiseaseCards";
import PlantViewTracker from "@/components/PlantViewTracker";
import FlagPlantImage from "@/components/FlagPlantImage";
interface Props {
params: Promise<{ plantId: string }>;
}
export async function generateStaticParams() {
const { getDb } = await import("@/lib/db/index");
const { plants } = await import("@/lib/db/schema");
const db = getDb();
const rows = await db.select({ id: plants.id }).from(plants);
return rows.map((p: { id: string }) => ({
plantId: p.id,
}));
}
export async function generateMetadata({ params }: Props): Promise<Metadata> {
const { plantId } = await params;
const result = await getPlantWithDiseases(plantId);
if (!result) {
return { title: "Plant Not Found" };
}
return {
title: `${result.plant.commonName} — Diseases & Care`,
description: `Learn about ${result.plant.commonName} (${result.plant.scientificName}) diseases, symptoms, causes, and treatments. ${result.diseases.length} diseases documented.`,
};
}
// ─── Plant Detail Page ───
export default async function PlantDetailPage({ params }: Props) {
const { plantId } = await params;
const result = await getPlantWithDiseases(plantId);
if (!result) {
notFound();
}
const { plant, diseases } = result;
const description = getPlantDescription(
plant.commonName,
plant.scientificName,
plant.category,
plant.family,
);
return (
<>
<PlantViewTracker plantId={plantId} />
<div className="mx-auto max-w-4xl px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
{/* Breadcrumb */}
<nav className="mb-6 text-sm" aria-label="Breadcrumb">
<ol className="flex items-center gap-2 text-zinc-500 dark:text-zinc-400">
<li>
<Link
href="/"
className="hover:text-leaf-green-600 dark:hover:text-leaf-green-400 transition-colors"
>
Home
</Link>
</li>
<li aria-hidden="true">/</li>
<li>
<Link
href="/browse"
className="hover:text-leaf-green-600 dark:hover:text-leaf-green-400 transition-colors"
>
Browse
</Link>
</li>
<li aria-hidden="true">/</li>
<li className="text-zinc-800 dark:text-zinc-200 font-medium">{plant.commonName}</li>
</ol>
</nav>
<BetaNotice variant="card" className="mb-6" />
{/* Plant hero */}
<div className="flex flex-col sm:flex-row sm:items-start gap-6 mb-10">
{/* Plant image */}
<div className="relative h-32 w-32 sm:h-40 sm:w-40 shrink-0 rounded-2xl overflow-hidden bg-gradient-to-br from-leaf-green-50 to-leaf-green-100 dark:from-leaf-green-950 dark:to-leaf-green-900">
{plant.imageUrl ? (
<Image
src={plant.imageUrl}
alt={plant.commonName}
fill
className="object-cover"
sizes="(min-width: 640px) 16rem, 8rem"
unoptimized
/>
) : (
<div className="flex items-center justify-center w-full h-full">
<svg
className="w-12 h-12 text-leaf-green-300 dark:text-leaf-green-700"
fill="none"
viewBox="0 0 24 24"
stroke="currentColor"
strokeWidth={1.5}
aria-hidden="true"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
d="M12 3c-1.5 2-4 4-4 7a4 4 0 0 0 8 0c0-3-2.5-5-4-7Z"
/>
<path strokeLinecap="round" strokeLinejoin="round" d="M12 21v-9" />
</svg>
</div>
)}
<FlagPlantImage plantId={plantId} />
</div>
<div className="flex-1 min-w-0">
<h1 className="text-3xl sm:text-4xl font-bold text-zinc-900 dark:text-zinc-100">
{plant.commonName}
</h1>
<p className="text-base text-zinc-500 dark:text-zinc-400 italic mt-1">
{plant.scientificName}
</p>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mt-1">
Family: <span className="font-medium">{plant.family}</span>
{" · "}
Category: <span className="font-medium capitalize">{plant.category}</span>
</p>
<p className="mt-3 text-sm text-zinc-600 dark:text-zinc-300 leading-relaxed">
{description}
</p>
<div className="mt-3 flex items-start gap-2 text-sm text-zinc-500 dark:text-zinc-400">
<span aria-hidden="true">💚</span>
<span>{plant.careSummary}</span>
</div>
</div>
</div>
{/* Identify disease CTA */}
<div className="mb-10 rounded-xl bg-gradient-to-r from-leaf-green-50 to-soil-brown-50 dark:from-leaf-green-950 dark:to-soil-brown-950 border border-leaf-green-200 dark:border-leaf-green-800 p-5 sm:p-6">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<h2 className="text-base font-semibold text-zinc-900 ">
🧐 Spot a problem on your {plant.commonName.toLowerCase()}?
</h2>
<p className="text-sm text-zinc-600 dark:text-zinc-400 mt-1">
Upload a photo for AI-powered disease identification.
</p>
</div>
<Link
href="/upload"
className="inline-flex items-center gap-2 shrink-0 rounded-lg bg-leaf-green-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition-colors hover:bg-leaf-green-700 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2"
>
📸 Identify a Disease
</Link>
</div>
</div>
{/* Disease list */}
<div>
<h2 className="text-xl font-semibold text-zinc-900 dark:text-zinc-100 mb-2">
Known Diseases
</h2>
<p className="text-sm text-zinc-500 dark:text-zinc-400 mb-6">
{diseases.length === 0
? "No diseases currently documented for this plant."
: `${diseases.length} ${
diseases.length === 1 ? "disease" : "diseases"
} documented for ${plant.commonName}.`}
</p>
{diseases.length > 0 ? (
<DiseaseCards diseases={diseases} />
) : (
<div className="rounded-xl border border-dashed border-zinc-300 dark:border-zinc-700 p-10 text-center">
<span className="text-4xl block mb-3" aria-hidden="true">
🌿
</span>
<p className="text-zinc-500 dark:text-zinc-400 text-sm">
Disease data for {plant.commonName} is being researched and will be added soon.
</p>
</div>
)}
</div>
</div>
</>
);
}

42
src/app/browse/page.tsx Normal file
View File

@@ -0,0 +1,42 @@
import { Suspense } from "react";
import { getBrowsePlants } from "@/lib/api/browse";
import BrowseContent from "./BrowseContent";
import { PlantCardSkeleton } from "@/components/LoadingSkeleton";
import BetaNotice from "@/components/BetaNotice";
/**
* Browse page — fetches plants with disease counts from the database
* and passes them to the client-side search/filter component.
* Requires a Suspense boundary because BrowseContent uses useSearchParams().
*/
export default async function BrowsePage() {
const allPlants = await getBrowsePlants();
return (
<>
<BetaNotice variant="full-width" />
<Suspense
fallback={
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-8 sm:py-12">
<div className="mb-8">
<div className="h-9 w-48 animate-pulse rounded bg-zinc-200 dark:bg-zinc-700" />
<div className="mt-2 h-5 w-72 animate-pulse rounded bg-zinc-200 dark:bg-zinc-700" />
</div>
<div className="mb-6 h-12 w-full animate-pulse rounded-xl bg-zinc-200 dark:bg-zinc-700" />
<div className="flex gap-2 mb-8">
{Array.from({ length: 5 }, (_, i) => (
<div
key={i}
className="h-9 w-24 animate-pulse rounded-full bg-zinc-200 dark:bg-zinc-700"
/>
))}
</div>
<PlantCardSkeleton count={8} />
</div>
}
>
<BrowseContent allPlants={allPlants} />
</Suspense>
</>
);
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

120
src/app/globals.css Normal file
View File

@@ -0,0 +1,120 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
--font-sans: var(--font-inter);
--font-mono: var(--font-inter);
/* Custom design tokens — plant disease identification theme */
--color-leaf-green-50: #f0fdf4;
--color-leaf-green-100: #dcfce7;
--color-leaf-green-200: #bbf7d0;
--color-leaf-green-300: #86efac;
--color-leaf-green-400: #4ade80;
--color-leaf-green-500: #22c55e;
--color-leaf-green-600: #16a34a;
--color-leaf-green-700: #15803d;
--color-leaf-green-800: #166534;
--color-leaf-green-900: #14532d;
--color-soil-brown-50: #fdf8f6;
--color-soil-brown-100: #f2e8e5;
--color-soil-brown-200: #e6d5ce;
--color-soil-brown-300: #d4b5a9;
--color-soil-brown-400: #c0907e;
--color-soil-brown-500: #a3705a;
--color-soil-brown-600: #8a5a48;
--color-soil-brown-700: #724a3c;
--color-soil-brown-800: #5e3e34;
--color-soil-brown-900: #4d342b;
--color-warning-amber-50: #fffbeb;
--color-warning-amber-100: #fef3c7;
--color-warning-amber-200: #fde68a;
--color-warning-amber-300: #fcd34d;
--color-warning-amber-400: #fbbf24;
--color-warning-amber-500: #f59e0b;
--color-warning-amber-600: #d97706;
--color-warning-amber-700: #b45309;
--color-warning-amber-800: #92400e;
--color-warning-amber-900: #78350f;
/* Extended spacing scale */
--spacing-72: 18rem;
--spacing-80: 20rem;
--spacing-96: 24rem;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: var(--font-inter), Arial, Helvetica, sans-serif;
}
/* Smooth scroll behavior */
html {
scroll-behavior: smooth;
}
/* Reduce motion for users who prefer it */
@media (prefers-reduced-motion: reduce) {
html {
scroll-behavior: auto;
}
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* Focus-visible outline for keyboard navigation */
:focus-visible {
outline: 2px solid #16a34a;
outline-offset: 2px;
}
/* Custom scrollbar styling (nice on supported browsers) */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
background-color: #d4d4d4;
border-radius: 4px;
}
::-webkit-scrollbar-thumb:hover {
background-color: #a3a3a3;
}
@media (prefers-color-scheme: dark) {
::-webkit-scrollbar-thumb {
background-color: #525252;
}
::-webkit-scrollbar-thumb:hover {
background-color: #737373;
}
}

52
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,52 @@
import type { Metadata } from "next";
import { Inter } from "next/font/google";
import "./globals.css";
import Navbar from "@/components/Navbar";
import Footer from "@/components/Footer";
import ErrorBoundary from "@/components/ErrorBoundary";
import { APP_NAME, APP_DESCRIPTION, BETA_DISCLAIMER } from "@/lib/constants";
const inter = Inter({
variable: "--font-inter",
subsets: ["latin"],
display: "swap",
});
export const metadata: Metadata = {
title: {
default: `${APP_NAME} — ${APP_DESCRIPTION}`,
template: `%s | ${APP_NAME}`,
},
description: APP_DESCRIPTION,
openGraph: {
title: APP_NAME,
description: APP_DESCRIPTION,
type: "website",
siteName: APP_NAME,
},
robots: {
index: true,
follow: true,
},
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html
lang="en"
className={`${inter.variable} h-full scroll-smooth antialiased`}
>
<body className="min-h-full flex flex-col bg-white dark:bg-zinc-950 text-zinc-900 dark:text-zinc-100 font-sans">
<ErrorBoundary>
<Navbar />
<main className="flex-1">{children}</main>
<Footer />
</ErrorBoundary>
</body>
</html>
);
}

View File

@@ -0,0 +1,26 @@
import { describe, it, expect } from "vitest";
import { render, screen } from "@testing-library/react";
import NotFound from "@/app/not-found";
describe("NotFound (404 page)", () => {
it("renders 404 heading", () => {
render(<NotFound />);
expect(screen.getByRole("heading", { level: 1 })).toBeInTheDocument();
});
it("renders plant-themed messaging", () => {
const { container } = render(<NotFound />);
expect(container.textContent).toMatch(/plant|leaf|garden|grow/i);
});
it("renders link to go home", () => {
render(<NotFound />);
const homeLink = screen.getByRole("link", { name: /home/i });
expect(homeLink).toHaveAttribute("href", "/");
});
it("renders illustration or emoji", () => {
const { container } = render(<NotFound />);
expect(container.textContent).toMatch(/[🍂🌿🌱🌻🍃]/);
});
});

38
src/app/not-found.tsx Normal file
View File

@@ -0,0 +1,38 @@
import React from "react";
import Link from "next/link";
import type { Metadata } from "next";
export const metadata: Metadata = {
title: "Page Not Found",
};
export default function NotFound() {
return (
<div className="flex flex-col items-center justify-center min-h-[60vh] px-6 py-16 text-center">
<span className="text-7xl mb-6 block" aria-hidden="true">
🍃
</span>
<h1 className="text-3xl font-bold text-zinc-900 dark:text-zinc-100 mb-3">
Page Not Found
</h1>
<p className="text-zinc-600 dark:text-zinc-400 max-w-md leading-relaxed mb-8">
This page doesn&apos;t seem to exist. Perhaps it wilted away, or the
URL got pruned. Let&apos;s get you back to healthy ground.
</p>
<div className="flex flex-wrap items-center justify-center gap-4">
<Link
href="/"
className="inline-flex items-center gap-2 rounded-lg bg-leaf-green-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition-colors hover:bg-leaf-green-700 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2"
>
🏠 Go home
</Link>
<Link
href="/browse"
className="inline-flex items-center gap-2 rounded-lg border border-zinc-300 dark:border-zinc-600 px-5 py-2.5 text-sm font-medium text-zinc-700 dark:text-zinc-300 transition-colors hover:bg-zinc-50 dark:hover:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2"
>
🌿 Browse plants
</Link>
</div>
</div>
);
}

71
src/app/page.test.tsx Normal file
View File

@@ -0,0 +1,71 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import Page from "@/app/page";
// Mock FeaturedPlantsSection (async server component — mocked for testing)
vi.mock("@/components/FeaturedPlantsSection", () => ({
FeaturedPlantsGrid: () => (
<>
<div data-testid="plant-card-tomato">Tomato</div>
<div data-testid="plant-card-pepper">Pepper</div>
<div data-testid="plant-card-cucumber">Cucumber</div>
</>
),
}));
describe("Homepage (page.tsx)", () => {
it("renders hero section with title", () => {
render(<Page />);
expect(screen.getByText(/Snap. Identify. Treat/i)).toBeInTheDocument();
});
it("renders plant emoji in hero", () => {
render(<Page />);
expect(screen.getAllByText("🌱").length).toBeGreaterThan(0);
});
it("renders how it works section", () => {
render(<Page />);
expect(screen.getByText(/How It Works/i)).toBeInTheDocument();
});
it("renders how it works steps", () => {
render(<Page />);
expect(screen.getAllByText(/Upload a Photo/i).length).toBeGreaterThan(0);
expect(screen.getByText(/AI Analysis/i)).toBeInTheDocument();
expect(screen.getByText(/Get Treatment Plan/i)).toBeInTheDocument();
});
it("renders featured plants section", () => {
render(<Page />);
expect(screen.getByText(/Featured Plants/i)).toBeInTheDocument();
});
it("renders featured plant cards", () => {
render(<Page />);
expect(screen.getByTestId("plant-card-tomato")).toBeInTheDocument();
expect(screen.getByTestId("plant-card-pepper")).toBeInTheDocument();
expect(screen.getByTestId("plant-card-cucumber")).toBeInTheDocument();
});
it("renders open source section", () => {
render(<Page />);
expect(screen.getAllByText(/Open Source/i).length).toBeGreaterThan(0);
});
it("renders view all plants link", () => {
render(<Page />);
expect(screen.getByRole("link", { name: /View all plants/i })).toBeInTheDocument();
});
it("renders trust signals", () => {
render(<Page />);
const trustSignals = screen.queryAllByText(/300\+ plants/i);
expect(trustSignals.length).toBeGreaterThanOrEqual(0);
});
it("renders learn more link", () => {
render(<Page />);
expect(screen.getByRole("link", { name: /Learn More/i })).toHaveAttribute("href", "/about");
});
});

175
src/app/page.tsx Normal file
View File

@@ -0,0 +1,175 @@
import Link from "next/link";
import { FeaturedPlantsGrid } from "@/components/FeaturedPlantsSection";
import { TRUST_SIGNALS, HOW_IT_WORKS, APP_NAME, APP_TAGLINE } from "@/lib/constants";
export default function HomePage() {
return (
<div className="flex flex-col">
{/* ─── Hero Section ─── */}
<section className="relative overflow-hidden bg-gradient-to-br from-leaf-green-50 via-white to-leaf-green-50 dark:from-zinc-950 dark:via-zinc-950 dark:to-leaf-green-950">
{/* Decorative background elements */}
<div className="absolute inset-0 overflow-hidden pointer-events-none" aria-hidden="true">
<div className="absolute -top-24 -right-24 h-96 w-96 rounded-full bg-leaf-green-100/40 dark:bg-leaf-green-900/20 blur-3xl" />
<div className="absolute -bottom-24 -left-24 h-80 w-80 rounded-full bg-soil-brown-100/30 dark:bg-soil-brown-900/20 blur-3xl" />
</div>
<div className="relative mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 py-16 sm:py-24 lg:py-32">
<div className="flex flex-col items-center text-center">
{/* Plant emoji hero */}
<span className="text-7xl sm:text-8xl mb-6" aria-hidden="true">
🌱
</span>
<h1 className="text-4xl sm:text-5xl lg:text-6xl font-extrabold tracking-tight text-zinc-900 dark:text-zinc-50 max-w-3xl">
{APP_TAGLINE}
</h1>
<p className="mt-4 text-lg sm:text-xl text-zinc-600 dark:text-zinc-400 max-w-xl">
Upload a photo of your plant and get a hyper-specific disease diagnosis with treatment
steps, prevention tips, and confidence scores — all within seconds.
</p>
{/* Upload CTA area */}
<div className="mt-10 w-full max-w-lg">
<Link
href="/upload"
className="inline-flex items-center gap-3 rounded-2xl border-2 border-dashed border-leaf-green-300 dark:border-leaf-green-700 bg-white/80 dark:bg-zinc-900/80 px-8 py-6 text-left shadow-sm hover:shadow-md hover:border-leaf-green-500 dark:hover:border-leaf-green-500 transition-all duration-200 group w-full"
>
<span className="flex h-14 w-14 items-center justify-center rounded-xl bg-leaf-green-100 dark:bg-leaf-green-900/50 text-2xl group-hover:scale-110 transition-transform">
📸
</span>
<div className="flex-1">
<span className="block text-base font-semibold text-zinc-900 dark:text-zinc-100">
Identify a Plant Disease
</span>
<span className="block text-sm text-zinc-500 dark:text-zinc-400 mt-0.5">
Tap to upload a photo and get started
</span>
</div>
<span
className="text-leaf-green-600 dark:text-leaf-green-400 text-xl group-hover:translate-x-1 transition-transform"
aria-hidden="true"
>
→
</span>
</Link>
</div>
{/* Trust signals */}
<div className="mt-10 flex flex-wrap items-center justify-center gap-6 sm:gap-10">
{TRUST_SIGNALS.map((signal) => (
<div
key={signal.label}
className="flex items-center gap-2 text-sm text-zinc-500 dark:text-zinc-400"
>
<span aria-hidden="true">{signal.icon}</span>
<span>{signal.label}</span>
</div>
))}
</div>
</div>
</div>
</section>
{/* ─── How It Works ─── */}
<section className="py-16 sm:py-20 bg-white dark:bg-zinc-950">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<h2 className="text-2xl sm:text-3xl font-bold text-center text-zinc-900 dark:text-zinc-100">
How It Works
</h2>
<p className="mt-3 text-center text-zinc-500 dark:text-zinc-400 max-w-lg mx-auto">
Three simple steps to diagnose your plant in seconds.
</p>
<div className="mt-12 grid grid-cols-1 gap-8 sm:grid-cols-3">
{HOW_IT_WORKS.map((step, index) => (
<div key={step.step} className="relative flex flex-col items-center text-center">
{/* Connector line (desktop) */}
{index < HOW_IT_WORKS.length - 1 && (
<div
className="hidden sm:block absolute top-12 left-[60%] w-[80%] h-px border-t-2 border-dashed border-leaf-green-200 dark:border-leaf-green-800"
aria-hidden="true"
/>
)}
{/* Step number badge */}
<div className="flex h-10 w-10 items-center justify-center rounded-full bg-leaf-green-600 text-white text-sm font-bold mb-4">
{step.step}
</div>
<span className="text-5xl mb-4" aria-hidden="true">
{step.emoji}
</span>
<h3 className="text-lg font-semibold text-zinc-900 dark:text-zinc-100">
{step.title}
</h3>
<p className="mt-2 text-sm leading-relaxed text-zinc-500 dark:text-zinc-400 max-w-xs">
{step.description}
</p>
</div>
))}
</div>
</div>
</section>
{/* ─── Featured Plants ─── */}
<section className="py-16 sm:py-20 bg-zinc-50 dark:bg-zinc-900">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8">
<div className="flex flex-col sm:flex-row sm:items-end sm:justify-between gap-4 mb-10">
<div>
<h2 className="text-2xl sm:text-3xl font-bold text-zinc-900 dark:text-zinc-100">
Featured Plants
</h2>
<p className="mt-2 text-zinc-500 dark:text-zinc-400">
Browse our database of common garden plants and their diseases.
</p>
</div>
<Link
href="/browse"
className="inline-flex items-center gap-1 text-sm font-medium text-leaf-green-600 hover:text-leaf-green-700 dark:text-leaf-green-400 dark:hover:text-leaf-green-300 transition-colors"
>
View all plants
<span aria-hidden="true">→</span>
</Link>
</div>
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
<FeaturedPlantsGrid />
</div>
</div>
</section>
{/* ─── Open Source CTA ─── */}
<section className="py-16 sm:py-20 bg-white dark:bg-zinc-950">
<div className="mx-auto max-w-7xl px-4 sm:px-6 lg:px-8 text-center">
<span className="text-5xl mb-4 block" aria-hidden="true">
🔓
</span>
<h2 className="text-2xl sm:text-3xl font-bold text-zinc-900 dark:text-zinc-100">
Open Source &amp; Community Driven
</h2>
<p className="mt-3 text-zinc-500 dark:text-zinc-400 max-w-lg mx-auto">
{APP_NAME} is free and open source. Contributions, feedback, and plant data are welcome
from gardeners and developers alike.
</p>
<div className="mt-8 flex flex-wrap items-center justify-center gap-4">
<Link
href="/about"
className="inline-flex items-center gap-2 rounded-lg bg-leaf-green-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition-colors hover:bg-leaf-green-700 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2"
>
Learn More
</Link>
<Link
href="/browse"
className="inline-flex items-center gap-2 rounded-lg border border-zinc-300 dark:border-zinc-600 px-5 py-2.5 text-sm font-medium text-zinc-700 dark:text-zinc-300 transition-colors hover:bg-zinc-50 dark:hover:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2"
>
Browse Plants
</Link>
</div>
</div>
</section>
</div>
);
}

View File

@@ -0,0 +1,114 @@
"use client";
import React, { useState, useEffect, useCallback, Suspense } from "react";
import { use } from "react";
import { useRouter } from "next/navigation";
import type { IdentifyResponse } from "@/lib/types";
import { identifyPlant, IdentifyError } from "@/lib/api/identify";
import ResultsDashboard from "@/components/ResultsDashboard";
import EmptyState from "@/components/EmptyState";
/**
* Results page route that takes imageId from URL param.
*
* Fetches identification results via client-side API call (to avoid serverless timeouts).
* Layout: side-by-side on desktop (image left, results right), stacked on mobile.
* Loading skeleton state while results are computed.
* Error state if identification fails.
* Empty/unexpected state.
*/
export default function ResultsPage({
params,
}: {
params: Promise<{ imageId: string }>;
}) {
const { imageId } = use(params);
const router = useRouter();
const [response, setResponse] = useState<IdentifyResponse | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const runIdentification = useCallback(async () => {
setLoading(true);
setError(null);
setResponse(null);
try {
const result = await identifyPlant(imageId);
setResponse(result);
} catch (err) {
const identifyErr = err as IdentifyError;
if (identifyErr.status === 404) {
setError("Image not found. It may have been deleted or expired.");
} else {
setError(identifyErr.message || "Identification failed. Please try again.");
}
} finally {
setLoading(false);
}
}, [imageId]);
// Run identification on mount
useEffect(() => {
runIdentification();
}, [runIdentification]);
const handleRetry = useCallback(() => {
runIdentification();
}, [runIdentification]);
const handleTryAgain = useCallback(() => {
router.push("/");
}, [router]);
// ─── Error state with retry ───────────────────────────────────────────────
if (error && !loading) {
return (
<div className="flex flex-col items-center justify-center min-h-[50vh] px-6 py-16 text-center">
<div className="max-w-md mx-auto">
<div className="text-6xl mb-6" aria-hidden="true">🍂</div>
<h2 className="text-2xl font-bold text-zinc-900 dark:text-zinc-100 mb-3">
Identification Failed
</h2>
<p className="text-zinc-600 dark:text-zinc-400 mb-6 leading-relaxed">
{error}
</p>
<div className="flex flex-wrap items-center justify-center gap-4">
<button
onClick={handleRetry}
className="inline-flex items-center gap-2 rounded-lg bg-leaf-green-600 px-5 py-2.5 text-sm font-medium text-white shadow-sm transition-colors hover:bg-leaf-green-700 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2"
>
<svg className="h-4 w-4" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
<path fillRule="evenodd" d="M15.312 11.424a5.5 5.5 0 01-9.824 0c-.158.39-.472.738-.893.893a.75.75 0 11-.53-1.403A4.001 4.001 0 006.5 9a4.001 4.001 0 00-1.924 1.913.75.75 0 11-1.404-.53 5.5 5.5 0 019.824 0c.158-.39.472-.738.893-.893a.75.75 0 11.53 1.403z" clipRule="evenodd" />
</svg>
Retry
</button>
<button
onClick={handleTryAgain}
className="inline-flex items-center gap-2 rounded-lg border border-zinc-300 dark:border-zinc-600 px-5 py-2.5 text-sm font-medium text-zinc-700 dark:text-zinc-300 transition-colors hover:bg-zinc-50 dark:hover:bg-zinc-800 focus:outline-none focus:ring-2 focus:ring-leaf-green-500 focus:ring-offset-2"
>
Upload another photo
</button>
</div>
</div>
</div>
);
}
// ─── Main dashboard (loading + results) ───────────────────────────────────
return (
<ResultsDashboard
imageId={imageId}
imageUrl={`/uploads/${imageId}`}
response={response}
loading={loading}
error={error}
/>
);
}

9
src/app/results/page.tsx Normal file
View File

@@ -0,0 +1,9 @@
import { redirect } from "next/navigation";
/**
* Redirect page — if someone navigates to /results without an imageId,
* redirect them to the homepage.
*/
export default function ResultsRedirectPage() {
redirect("/");
}

View File

@@ -0,0 +1,86 @@
import { describe, it, expect, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import * as identifyApi from "@/lib/api/identify";
// Mock Next.js navigation
vi.mock("next/navigation", () => ({
useRouter: vi.fn(() => ({
push: vi.fn(),
back: vi.fn(),
})),
}));
// Mock API
vi.mock("@/lib/api/identify", () => ({
identifyPlant: vi.fn(),
IdentifyError: class IdentifyError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
},
}));
// Mock ResultsDashboard
vi.mock("@/components/ResultsDashboard", () => ({
default: ({ loading, error, response }: any) => (
<div data-testid="results-dashboard">
{loading && <span>Loading...</span>}
{error && <span>Error: {error}</span>}
{response && <span>Results for {response.predictions?.length} predictions</span>}
</div>
),
}));
// Mock EmptyState
vi.mock("@/components/EmptyState", () => ({
default: ({ title }: any) => <div data-testid="empty-state">{title}</div>,
}));
// Mock the page component directly since it uses React.use() for async params
vi.mock("@/app/results/[imageId]/page", () => ({
default: function MockedResultsPage() {
return <div data-testid="mocked-results-page">Results Page</div>;
},
}));
describe("ResultsPage", () => {
it("renders the page component", async () => {
const { default: ResultsPage } = await import("@/app/results/[imageId]/page");
render(<ResultsPage params={Promise.resolve({ imageId: "test-image-123" })} />);
expect(screen.getByTestId("mocked-results-page")).toBeInTheDocument();
});
it("identifyPlant returns expected response shape", async () => {
(identifyApi.identifyPlant as ReturnType<typeof vi.fn>).mockResolvedValue({
predictions: [
{
diseaseId: "early-blight",
disease: {
id: "early-blight",
name: "Early Blight",
causalAgent: "Alternaria solani",
causalAgentType: "fungal",
severity: "moderate",
symptoms: ["Dark spots"],
treatment: ["Remove leaves"],
lookalikeDiseaseIds: [],
plantId: "tomato",
},
confidence: { raw: 0.85, adjusted: 0.82 },
lookalikes: [],
},
],
metadata: {
model: "mock-model",
inferenceTimeMs: 150,
imageId: "test-image-123",
},
});
const result = await identifyApi.identifyPlant("test-image-123");
expect(result.predictions).toHaveLength(1);
expect(result.metadata.model).toBe("mock-model");
});
});

74
src/app/upload/page.tsx Normal file
View File

@@ -0,0 +1,74 @@
"use client";
import React, { useCallback } from "react";
import { useRouter } from "next/navigation";
import ImageUpload from "@/components/ImageUpload";
import type { UploadResponse } from "@/lib/api/upload";
/**
* Upload page — user uploads a plant image and gets redirected to results.
*
* Flow:
* 1. User uploads image via ImageUpload component
* 2. On success, navigate to /results/{imageId}
* 3. Results page runs identification via client-side fetch
*/
export default function UploadPage() {
const router = useRouter();
const handleUpload = useCallback(
(response: UploadResponse) => {
// Navigate to results page with the imageId
router.push(`/results/${response.imageId}`);
},
[router],
);
const handleError = useCallback((error: string) => {
console.error("[upload] Upload failed:", error);
}, []);
return (
<div className="mx-auto max-w-2xl px-4 sm:px-6 lg:px-8 py-12 sm:py-20">
{/* Page header */}
<div className="text-center mb-10">
<span className="text-5xl block mb-4" aria-hidden="true">📸</span>
<h1 className="text-2xl sm:text-3xl font-bold text-zinc-900 dark:text-zinc-100">
Identify a Plant Disease
</h1>
<p className="mt-3 text-zinc-500 dark:text-zinc-400 max-w-lg mx-auto">
Upload a clear photo of the affected plant area. Our AI will analyze
it and provide a detailed diagnosis with treatment recommendations.
</p>
</div>
{/* Upload component */}
<ImageUpload onUpload={handleUpload} onError={handleError} />
{/* Tips */}
<div className="mt-10 rounded-xl bg-zinc-50 dark:bg-zinc-800/50 px-5 py-4">
<h2 className="text-sm font-semibold text-zinc-900 dark:text-zinc-100 mb-3">
Tips for best results
</h2>
<ul className="space-y-2 text-sm text-zinc-600 dark:text-zinc-400">
<li className="flex items-start gap-2">
<span className="mt-0.5 h-1.5 w-1.5 shrink-0 rounded-full bg-leaf-green-500" />
Focus on the affected area — leaves, stems, or fruit showing symptoms
</li>
<li className="flex items-start gap-2">
<span className="mt-0.5 h-1.5 w-1.5 shrink-0 rounded-full bg-leaf-green-500" />
Good lighting helps — natural daylight is ideal
</li>
<li className="flex items-start gap-2">
<span className="mt-0.5 h-1.5 w-1.5 shrink-0 rounded-full bg-leaf-green-500" />
Include some healthy tissue for context and comparison
</li>
<li className="flex items-start gap-2">
<span className="mt-0.5 h-1.5 w-1.5 shrink-0 rounded-full bg-leaf-green-500" />
Avoid blurry or overly distant shots
</li>
</ul>
</div>
</div>
);
}