import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { serveStatic } from 'hono/cloudflare-workers'

const app = new Hono()

app.use('*', cors())

// In-memory storage (for Cloudflare Workers - use KV in production)
// We'll use a global store pattern
declare global {
  var farmersDB: Map<string, any>
  var documentsDB: Map<string, any[]>
  var sessionsDB: Map<string, string>
}

if (!globalThis.farmersDB) globalThis.farmersDB = new Map()
if (!globalThis.documentsDB) globalThis.documentsDB = new Map()
if (!globalThis.sessionsDB) globalThis.sessionsDB = new Map()

// Utility: generate unique farmer ID
function generateFarmerID(): string {
  const prefix = 'KKH'
  const year = new Date().getFullYear()
  const rand = Math.floor(1000 + Math.random() * 9000)
  return `${prefix}-${year}-${rand}`
}

// Utility: generate password
function generatePassword(): string {
  const chars = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
  let password = ''
  for (let i = 0; i < 8; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  return password
}

// Static files
app.use('/static/*', serveStatic({ root: './' }))

// Favicon
app.get('/favicon.svg', (c) => {
  return c.redirect('/kkh-logo.png', 302)
})
app.get('/favicon.ico', (c) => {
  return c.redirect('/kkh-logo.png', 302)
})

// ─── API ROUTES ───────────────────────────────────────────────────────────────

// Register new farmer (creates account)
app.post('/api/register', async (c) => {
  const body = await c.req.json()
  const { email, fullName } = body

  if (!email || !fullName) {
    return c.json({ success: false, message: 'Email and full name are required' }, 400)
  }

  // Check if email already exists
  for (const [, farmer] of globalThis.farmersDB) {
    if (farmer.email === email) {
      return c.json({ success: false, message: 'An account with this email already exists. Please login.' }, 409)
    }
  }

  const farmerID = generateFarmerID()
  const password = generatePassword()
  const now = new Date().toISOString()

  const farmerData = {
    farmerID,
    email,
    fullName,
    password,
    status: 'pending',
    progress: 0,
    createdAt: now,
    updatedAt: now,
    applicationData: { sectionA: { fullName, email } },
    completedSections: ['A'],
    documentsUploaded: []
  }

  globalThis.farmersDB.set(farmerID, farmerData)

  return c.json({
    success: true,
    farmerID,
    password,
    message: 'Account created successfully. Please save your login credentials.'
  })
})

// Login
app.post('/api/login', async (c) => {
  const body = await c.req.json()
  const { farmerID, password } = body

  const farmer = globalThis.farmersDB.get(farmerID)
  if (!farmer || farmer.password !== password) {
    return c.json({ success: false, message: 'Invalid Farmer ID or password' }, 401)
  }

  // Create session token
  const sessionToken = btoa(`${farmerID}:${Date.now()}:${Math.random()}`)
  globalThis.sessionsDB.set(sessionToken, farmerID)

  return c.json({
    success: true,
    sessionToken,
    farmerID,
    fullName: farmer.fullName,
    email: farmer.email,
    progress: farmer.progress,
    status: farmer.status,
    applicationData: farmer.applicationData,
    completedSections: farmer.completedSections
  })
})

// Save application progress
app.post('/api/application/save', async (c) => {
  const sessionToken = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!sessionToken) return c.json({ success: false, message: 'Unauthorized' }, 401)

  const farmerID = globalThis.sessionsDB.get(sessionToken)
  if (!farmerID) return c.json({ success: false, message: 'Session expired' }, 401)

  const farmer = globalThis.farmersDB.get(farmerID)
  if (!farmer) return c.json({ success: false, message: 'Farmer not found' }, 404)

  const body = await c.req.json()
  const { section, data, progress } = body

  farmer.applicationData = { ...farmer.applicationData, ...data }
  if (section && !farmer.completedSections.includes(section)) {
    farmer.completedSections.push(section)
  }
  if (progress !== undefined) farmer.progress = progress
  farmer.updatedAt = new Date().toISOString()

  globalThis.farmersDB.set(farmerID, farmer)

  return c.json({ success: true, message: 'Progress saved successfully', progress: farmer.progress })
})

// Get farmer profile
app.get('/api/farmer/profile', async (c) => {
  const sessionToken = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!sessionToken) return c.json({ success: false, message: 'Unauthorized' }, 401)

  const farmerID = globalThis.sessionsDB.get(sessionToken)
  if (!farmerID) return c.json({ success: false, message: 'Session expired' }, 401)

  const farmer = globalThis.farmersDB.get(farmerID)
  if (!farmer) return c.json({ success: false, message: 'Farmer not found' }, 404)

  const { password: _, ...safeData } = farmer
  return c.json({ success: true, farmer: safeData })
})

// Submit final application
app.post('/api/application/submit', async (c) => {
  const sessionToken = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!sessionToken) return c.json({ success: false, message: 'Unauthorized' }, 401)

  const farmerID = globalThis.sessionsDB.get(sessionToken)
  if (!farmerID) return c.json({ success: false, message: 'Session expired' }, 401)

  const farmer = globalThis.farmersDB.get(farmerID)
  if (!farmer) return c.json({ success: false, message: 'Farmer not found' }, 404)

  const body = await c.req.json()
  farmer.applicationData = { ...farmer.applicationData, ...body }
  farmer.status = 'submitted'
  farmer.progress = 100
  farmer.submittedAt = new Date().toISOString()
  farmer.updatedAt = new Date().toISOString()

  globalThis.farmersDB.set(farmerID, farmer)

  return c.json({ success: true, message: 'Application submitted successfully! We will review your application and contact you within 5 business days.' })
})

// ─── ADMIN ROUTES ─────────────────────────────────────────────────────────────

// Admin login (simple for demo)
app.post('/api/admin/login', async (c) => {
  const body = await c.req.json()
  const { username, password } = body

  if (username === 'admin@khanyakhwezi.co.za' && password === 'KKH@Admin2024') {
    const token = btoa(`admin:${Date.now()}`)
    globalThis.sessionsDB.set(token, 'ADMIN')
    return c.json({ success: true, token, role: 'admin' })
  }

  return c.json({ success: false, message: 'Invalid admin credentials' }, 401)
})

// Get all farmers (admin only)
app.get('/api/admin/farmers', async (c) => {
  const token = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!token || globalThis.sessionsDB.get(token) !== 'ADMIN') {
    return c.json({ success: false, message: 'Unauthorized' }, 401)
  }

  const farmers: any[] = []
  for (const [, farmer] of globalThis.farmersDB) {
    const { password: _, ...safeData } = farmer
    farmers.push(safeData)
  }

  return c.json({ success: true, farmers, total: farmers.length })
})

// Get single farmer (admin only)
app.get('/api/admin/farmers/:id', async (c) => {
  const token = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!token || globalThis.sessionsDB.get(token) !== 'ADMIN') {
    return c.json({ success: false, message: 'Unauthorized' }, 401)
  }

  const farmerID = c.req.param('id')
  const farmer = globalThis.farmersDB.get(farmerID)
  if (!farmer) return c.json({ success: false, message: 'Farmer not found' }, 404)

  const { password: _, ...safeData } = farmer
  return c.json({ success: true, farmer: safeData })
})

// Update farmer status (admin only)
app.patch('/api/admin/farmers/:id/status', async (c) => {
  const token = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!token || globalThis.sessionsDB.get(token) !== 'ADMIN') {
    return c.json({ success: false, message: 'Unauthorized' }, 401)
  }

  const farmerID = c.req.param('id')
  const farmer = globalThis.farmersDB.get(farmerID)
  if (!farmer) return c.json({ success: false, message: 'Farmer not found' }, 404)

  const { status, comments } = await c.req.json()
  farmer.status = status
  farmer.adminComments = comments
  farmer.updatedAt = new Date().toISOString()

  globalThis.farmersDB.set(farmerID, farmer)

  return c.json({ success: true, message: `Status updated to ${status}` })
})

// Export farmers as CSV (admin only)
app.get('/api/admin/export/csv', async (c) => {
  const token = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!token || globalThis.sessionsDB.get(token) !== 'ADMIN') {
    return c.json({ success: false, message: 'Unauthorized' }, 401)
  }

  const headers = [
    'Farmer ID', 'Full Name', 'Email', 'Status', 'Progress %',
    'Farm Name', 'Farm Location', 'Land Ownership', 'Water Source',
    'Primary Crops', 'Production Volume', 'Business Registered',
    'Business Name', 'Tax Number', 'Employees', 'Bank Name',
    'Support Required', 'Created Date', 'Submitted Date', 'Admin Comments'
  ]

  const rows: string[] = [headers.join(',')]

  for (const [, farmer] of globalThis.farmersDB) {
    const ad = farmer.applicationData || {}
    const sA = ad.sectionA || {}
    const sB = ad.sectionB || {}
    const sC = ad.sectionC || {}
    const sE = ad.sectionE || {}
    const sF = ad.sectionF || {}

    const row = [
      farmer.farmerID,
      `"${sA.fullName || ''}"`,
      sA.email || '',
      farmer.status || 'pending',
      farmer.progress || 0,
      `"${sB.farmName || ''}"`,
      `"${sB.farmLocation || ''}"`,
      sB.landOwnership || '',
      sB.waterSource || '',
      `"${(sC.mainCrops || []).join('; ')}"`,
      sC.productionVolume || '',
      sE.registeredBusiness || '',
      `"${sE.businessName || ''}"`,
      sE.taxNumber || '',
      sE.employees || '',
      sE.bankName || '',
      `"${(sF.supportRequired || []).join('; ')}"`,
      farmer.createdAt || '',
      farmer.submittedAt || '',
      `"${farmer.adminComments || ''}"`
    ]
    rows.push(row.join(','))
  }

  const csv = rows.join('\n')

  return new Response(csv, {
    headers: {
      'Content-Type': 'text/csv',
      'Content-Disposition': `attachment; filename="KKH_Farmers_${new Date().toISOString().split('T')[0]}.csv"`
    }
  })
})

// Demo: seed some test farmers
app.post('/api/admin/seed', async (c) => {
  const token = c.req.header('Authorization')?.replace('Bearer ', '')
  if (!token || globalThis.sessionsDB.get(token) !== 'ADMIN') {
    return c.json({ success: false, message: 'Unauthorized' }, 401)
  }

  const sampleFarmers = [
    {
      farmerID: 'KKH-2024-1001',
      email: 'sipho.nkosi@gmail.com',
      fullName: 'Sipho Nkosi',
      password: 'Pass1234',
      status: 'submitted',
      progress: 100,
      createdAt: '2024-01-15T08:00:00Z',
      submittedAt: '2024-01-20T10:00:00Z',
      updatedAt: '2024-01-20T10:00:00Z',
      applicationData: {
        sectionA: { fullName: 'Sipho Nkosi', email: 'sipho.nkosi@gmail.com', idNumber: '7801015012345', gender: 'Male', primaryContact: '+27731234567', province: 'KwaZulu-Natal' },
        sectionB: { farmName: 'Nkosi Family Farm', farmLocation: 'Eshowe, KZN', landOwnership: 'Owned', waterSource: 'Borehole', irrigationInstalled: 'Yes' },
        sectionC: { produceCategories: ['Vegetables', 'Fruits'], mainCrops: ['Spinach', 'Tomatoes', 'Avocados'], productionVolume: '500kg/month', marketOutlets: ['Local Market'] },
        sectionD: { certifications: ['None'], trainingReceived: ['Agricultural'], reason: 'Seeking GAP certification to supply to retailers' },
        sectionE: { registeredBusiness: 'No', employees: '3', bankName: 'Standard Bank' },
        sectionF: { supportRequired: ['GAP Accreditation Support', 'Market Linkage'] }
      },
      completedSections: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
      documentsUploaded: ['ID Copy', 'Proof of Residence', 'Bank Statement']
    },
    {
      farmerID: 'KKH-2024-1002',
      email: 'thandi.dlamini@yahoo.com',
      fullName: 'Thandiswa Dlamini',
      password: 'Pass5678',
      status: 'approved',
      progress: 100,
      createdAt: '2024-02-01T09:00:00Z',
      submittedAt: '2024-02-05T14:00:00Z',
      updatedAt: '2024-02-10T11:00:00Z',
      applicationData: {
        sectionA: { fullName: 'Thandiswa Dlamini', email: 'thandi.dlamini@yahoo.com', idNumber: '8503120034567', gender: 'Female', primaryContact: '+27829876543', province: 'Limpopo' },
        sectionB: { farmName: 'Dlamini Acres', farmLocation: 'Tzaneen, Limpopo', landOwnership: 'Leased', waterSource: 'Municipal', irrigationInstalled: 'Yes' },
        sectionC: { produceCategories: ['Fruits'], mainCrops: ['Avocados', 'Mangoes', 'Potatoes'], productionVolume: '2 tons/month', marketOutlets: ['No Formal Market'] },
        sectionD: { certifications: ['GAP'], trainingReceived: ['Agricultural', 'Food Safety'], reason: 'Export readiness and market access' },
        sectionE: { registeredBusiness: 'Yes', businessName: 'Dlamini Agri CC', registrationNo: 'CK2023/12345', taxNumber: '1234567890', employees: '8', bankName: 'Absa' },
        sectionF: { supportRequired: ['HACCP Certification', 'Export Readiness', 'Quality Grading Training'] }
      },
      completedSections: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'],
      documentsUploaded: ['ID Copy', 'Proof of Residence', 'GAP Certificate', 'Bank Statement', 'Company Registration'],
      adminComments: 'Excellent application. Approved for market linkage.'
    },
    {
      farmerID: 'KKH-2024-1003',
      email: 'bongani.zulu@hotmail.com',
      fullName: 'Bongani Zulu',
      password: 'Pass9012',
      status: 'pending',
      progress: 60,
      createdAt: '2024-03-10T07:00:00Z',
      updatedAt: '2024-03-12T16:00:00Z',
      applicationData: {
        sectionA: { fullName: 'Bongani Zulu', email: 'bongani.zulu@hotmail.com', idNumber: '9012085034567', gender: 'Male', primaryContact: '+27651234567', province: 'Eastern Cape' },
        sectionB: { farmName: 'Zulu Community Farm', farmLocation: 'Mthatha, EC', landOwnership: 'Communal/Tribal', waterSource: 'Rain-fed', irrigationInstalled: 'No' },
        sectionC: { produceCategories: ['Vegetables', 'Livestock'], mainCrops: ['Maize', 'Butternut', 'Cattle'], productionVolume: '300kg/month', marketOutlets: ['Street Vendors'] }
      },
      completedSections: ['A', 'B', 'C'],
      documentsUploaded: ['ID Copy']
    }
  ]

  for (const farmer of sampleFarmers) {
    globalThis.farmersDB.set(farmer.farmerID, farmer)
  }

  return c.json({ success: true, message: `${sampleFarmers.length} sample farmers added` })
})

// ─── PAGE ROUTES ─────────────────────────────────────────────────────────────

// Main marketing website
app.get('/', (c) => {
  return c.html(mainWebsiteHTML())
})

// Farmer portal
app.get('/farmer-portal', (c) => {
  return c.html(farmerPortalHTML())
})

// Farmer application form
app.get('/apply', (c) => {
  return c.html(applicationFormHTML())
})

// Admin dashboard
app.get('/admin', (c) => {
  return c.html(adminDashboardHTML())
})

// Admin farmer detail page
app.get('/admin/farmer/:id', (c) => {
  return c.html(adminFarmerDetailHTML())
})

export default app

// ─── SHARED LOGO ─────────────────────────────────────────────────────────────

const LOGO_URL = '/kkh-logo.png'

// Original logo — square display, no circular clip, no border-radius
function kkhLogoHTML(size = 48, extraClass = ''): string {
  return `<div class="flex-shrink-0 ${extraClass}" style="width:${size}px;height:${size}px;flex-shrink:0;">
    <img src="${LOGO_URL}" alt="KhanyaKhwezi Harvesting" style="width:100%;height:100%;object-fit:contain;display:block;border-radius:0;">
  </div>`
}

// kkhLogoSVG kept as alias for backward-compat — square, no clip
function kkhLogoSVG(size = 120): string {
  return `<img src="${LOGO_URL}" alt="KhanyaKhwezi Harvesting" style="width:${size}px;height:${size}px;object-fit:contain;display:block;border-radius:0;">`
}

// ─── HTML PAGES ──────────────────────────────────────────────────────────────

function mainWebsiteHTML() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>KhanyaKhwezi Harvesting - From the Soil to the Shelf</title>
<link rel="icon" href="/kkh-logo.png">
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&family=Playfair+Display:wght@700;800&display=swap" rel="stylesheet">
<style>
  body { font-family: 'Inter', sans-serif; }
  .hero-gradient { background: linear-gradient(135deg, #0f2027 0%, #203a43 50%, #2c5364 100%); }
  .green-gradient { background: linear-gradient(135deg, #1a4731 0%, #2d6a4f 100%); }
  .gold-accent { color: #c9a84c; }
  .gold-bg { background: #c9a84c; }
  .section-gradient { background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%); }
  .card-hover { transition: all 0.3s ease; }
  .card-hover:hover { transform: translateY(-6px); box-shadow: 0 20px 40px rgba(0,0,0,0.12); }
  .nav-link { transition: color 0.2s; }
  .nav-link:hover { color: #c9a84c; }
  .fade-in { animation: fadeIn 0.8s ease-in-out; }
  @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } }
  .stat-counter { font-family: 'Playfair Display', serif; }
  .logo-circle { }
  .testimonial-card { border-left: 4px solid #c9a84c; }
  .feature-icon { background: linear-gradient(135deg, #1a4731, #2d6a4f); }
  ::-webkit-scrollbar { width: 8px; }
  ::-webkit-scrollbar-track { background: #f1f1f1; }
  ::-webkit-scrollbar-thumb { background: #2d6a4f; border-radius: 4px; }
</style>
</head>
<body class="bg-white">

<!-- Navigation -->
<nav class="fixed top-0 w-full z-50 bg-white/95 backdrop-blur-md shadow-sm border-b border-gray-100">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="flex justify-between items-center h-16">
      <div class="flex items-center space-x-3">
        ${kkhLogoHTML(48)}
        <div>
          <span class="font-bold text-gray-900 text-lg leading-tight block">KhanyaKhwezi</span>
          <span class="text-xs text-green-700 font-medium tracking-wide">HARVESTING</span>
        </div>
      </div>
      <div class="hidden md:flex items-center space-x-8">
        <a href="#about" class="nav-link text-gray-600 text-sm font-medium">About Us</a>
        <a href="#services" class="nav-link text-gray-600 text-sm font-medium">Services</a>
        <a href="#use-cases" class="nav-link text-gray-600 text-sm font-medium">Use Cases</a>
        <a href="#testimonials" class="nav-link text-gray-600 text-sm font-medium">Testimonials</a>
        <a href="#contact" class="nav-link text-gray-600 text-sm font-medium">Contact</a>
        <a href="/farmer-portal" class="bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-green-800 transition-colors">Farmer Portal</a>
      </div>
      <button id="mobileMenuBtn" class="md:hidden text-gray-600">
        <i class="fas fa-bars text-xl"></i>
      </button>
    </div>
  </div>
  <!-- Mobile Menu -->
  <div id="mobileMenu" class="hidden md:hidden bg-white border-t border-gray-100 px-4 py-4 space-y-3">
    <a href="#about" class="block text-gray-600 font-medium py-2">About Us</a>
    <a href="#services" class="block text-gray-600 font-medium py-2">Services</a>
    <a href="#use-cases" class="block text-gray-600 font-medium py-2">Use Cases</a>
    <a href="#testimonials" class="block text-gray-600 font-medium py-2">Testimonials</a>
    <a href="#contact" class="block text-gray-600 font-medium py-2">Contact</a>
    <a href="/farmer-portal" class="block bg-green-700 text-white px-4 py-3 rounded-lg font-semibold text-center">Farmer Portal</a>
  </div>
</nav>

<!-- Hero Section -->
<section class="hero-gradient min-h-screen flex items-center relative overflow-hidden pt-16">
  <div class="absolute inset-0 opacity-10">
    <div class="absolute top-20 right-20 w-64 h-64 rounded-full bg-yellow-400 blur-3xl"></div>
    <div class="absolute bottom-20 left-20 w-96 h-96 rounded-full bg-green-400 blur-3xl"></div>
  </div>
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-20 relative z-10">
    <div class="grid lg:grid-cols-2 gap-16 items-center">
      <div class="fade-in">
        <div class="inline-flex items-center bg-white/10 rounded-full px-3 py-2 mb-6 gap-3">
          <div style="width:32px;height:32px;flex-shrink:0;">${kkhLogoSVG(32)}</div>
          <span class="w-2 h-2 bg-green-400 rounded-full animate-pulse flex-shrink-0"></span>
          <span class="text-green-300 text-sm font-medium">Africa's Agricultural Marketplace</span>
        </div>
        <h1 class="text-5xl lg:text-7xl font-black text-white leading-tight mb-6">
          From The <br><span class="gold-accent">Soil</span> To The<br><span class="gold-accent">Shelf</span>
        </h1>
        <p class="text-gray-300 text-xl leading-relaxed mb-8 max-w-xl">
          KhanyaKhwezi Harvesting bridges the gap between local farmers and major retail markets — empowering previously disadvantaged black farmers through certification, compliance, and wholesale distribution.
        </p>
        <div class="flex flex-col sm:flex-row gap-4">
          <a href="#contact" class="gold-bg text-white px-8 py-4 rounded-xl font-bold text-lg hover:opacity-90 transition-opacity text-center shadow-lg">
            Request a Demo
          </a>
          <a href="/apply" class="bg-white/15 border border-white/30 text-white px-8 py-4 rounded-xl font-semibold text-lg hover:bg-white/25 transition-all text-center">
            <i class="fas fa-leaf mr-2"></i> Apply as Farmer
          </a>
        </div>
        <div class="mt-12 flex items-center gap-4">
          <div class="flex -space-x-2">
            <div class="w-9 h-9 rounded-full bg-green-500 border-2 border-white flex items-center justify-center text-white text-xs font-bold">S</div>
            <div class="w-9 h-9 rounded-full bg-yellow-500 border-2 border-white flex items-center justify-center text-white text-xs font-bold">T</div>
            <div class="w-9 h-9 rounded-full bg-blue-500 border-2 border-white flex items-center justify-center text-white text-xs font-bold">B</div>
          </div>
          <p class="text-gray-300 text-sm">Trusted by <strong class="text-white">100+ farmers</strong> across South Africa</p>
        </div>
      </div>
      <div class="hidden lg:flex flex-col items-center">
        <!-- Big Logo Display -->
        <div class="relative mb-6">
          <div style="width:220px;height:220px;position:relative;z-index:2;">
            ${kkhLogoSVG(220)}
          </div>
        </div>
        <!-- Brand name under logo -->
        <div class="text-center mb-6">
          <div class="text-white text-2xl font-black tracking-wide">KhanyaKhwezi</div>
          <div class="text-yellow-400 text-sm font-semibold tracking-[0.3em] uppercase mt-1">Harvesting</div>
          <div class="text-gray-400 text-xs mt-1 italic">From the Soil to the Shelf</div>
        </div>
        <!-- Stats row -->
        <div class="grid grid-cols-2 gap-3 w-full max-w-xs">
          <div class="bg-white/10 backdrop-blur-sm rounded-2xl p-4 text-center border border-white/20">
            <div class="stat-counter text-3xl font-bold text-green-400">4+</div>
            <div class="text-gray-300 text-xs mt-1">Export Markets</div>
          </div>
          <div class="bg-white/10 backdrop-blur-sm rounded-2xl p-4 text-center border border-white/20">
            <div class="stat-counter text-3xl font-bold text-yellow-400">100+</div>
            <div class="text-gray-300 text-xs mt-1">Active Farmers</div>
          </div>
        </div>
        <!-- Flags -->
        <div class="flex gap-2 mt-3 flex-wrap justify-center">
          ${['🇿🇦 SA','🇦🇪 UAE','🇮🇪 IE','🇹🇷 TR','🇭🇷 HR'].map(f => `<span class="bg-white/10 text-gray-200 text-xs px-3 py-1 rounded-full border border-white/20">${f}</span>`).join('')}
        </div>
        <div class="mt-3 bg-green-600/80 text-white rounded-xl px-5 py-2 text-xs font-semibold">
          GAP • HACCP • Food Safety Certified
        </div>
      </div>
    </div>
  </div>
  <div class="absolute bottom-0 left-0 right-0">
    <svg viewBox="0 0 1440 80" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M0 80L1440 80L1440 40C1200 0 720 80 0 40L0 80Z" fill="white"/>
    </svg>
  </div>
</section>

<!-- Stats Bar -->
<section class="bg-white py-12 shadow-sm">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="grid grid-cols-2 md:grid-cols-4 gap-8 text-center">
      <div>
        <div class="stat-counter text-4xl font-bold text-green-800">100+</div>
        <div class="text-gray-500 text-sm mt-1">Registered Farmers</div>
      </div>
      <div>
        <div class="stat-counter text-4xl font-bold text-green-800">4</div>
        <div class="text-gray-500 text-sm mt-1">Export Markets</div>
      </div>
      <div>
        <div class="stat-counter text-4xl font-bold text-green-800">GAP</div>
        <div class="text-gray-500 text-sm mt-1">Certified Program</div>
      </div>
      <div>
        <div class="stat-counter text-4xl font-bold text-green-800">2024</div>
        <div class="text-gray-500 text-sm mt-1">Est. KwaDukuza, KZN</div>
      </div>
    </div>
  </div>
</section>

<!-- About Section -->
<section id="about" class="section-gradient py-24">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="grid lg:grid-cols-2 gap-16 items-center">
      <div>
        <div class="inline-block bg-green-100 text-green-800 px-4 py-2 rounded-full text-sm font-semibold mb-4">Who We Are</div>
        <h2 class="text-4xl font-bold text-gray-900 mb-6 leading-tight">The Bridge Between <span class="text-green-700">Farming</span> and <span class="text-green-700">Markets</span></h2>
        <p class="text-gray-600 text-lg leading-relaxed mb-6">KhanyaKhwezi Harvesting operates at the critical intersection of agriculture and commerce. We are a specialized intermediary dedicated to harvesting and distributing fresh vegetation and livestock produce.</p>
        <p class="text-gray-600 leading-relaxed mb-8">By bridging the gap between local farmers and major retail markets, we create sustainable value chains that benefit both the producer and the consumer — from small-scale family farms to international export markets.</p>
        <div class="grid grid-cols-2 gap-4">
          <div class="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
            <div class="w-10 h-10 feature-icon rounded-lg flex items-center justify-center mb-3">
              <i class="fas fa-bullseye text-white"></i>
            </div>
            <h4 class="font-bold text-gray-900 mb-1">Our Mission</h4>
            <p class="text-gray-500 text-sm">Empowering local, previously disadvantaged black farmers through market access</p>
          </div>
          <div class="bg-white rounded-xl p-5 shadow-sm border border-gray-100">
            <div class="w-10 h-10 feature-icon rounded-lg flex items-center justify-center mb-3">
              <i class="fas fa-eye text-white"></i>
            </div>
            <h4 class="font-bold text-gray-900 mb-1">Our Vision</h4>
            <p class="text-gray-500 text-sm">Africa's leading agricultural intermediary connecting farms to global markets</p>
          </div>
        </div>
      </div>
      <div class="grid grid-cols-2 gap-4">
        <div class="space-y-4">
          <div class="bg-green-700 text-white rounded-2xl p-6 card-hover">
            <i class="fas fa-certificate text-3xl gold-accent mb-3 block"></i>
            <h4 class="font-bold mb-2">Accreditation Support</h4>
            <p class="text-green-100 text-sm">GAP, HACCP & Food Safety certification assistance</p>
          </div>
          <div class="bg-white border border-gray-200 rounded-2xl p-6 card-hover shadow-sm">
            <i class="fas fa-store text-3xl text-green-700 mb-3 block"></i>
            <h4 class="font-bold text-gray-900 mb-2">Retail Linkage</h4>
            <p class="text-gray-500 text-sm">Direct connections to major SA retail chains</p>
          </div>
        </div>
        <div class="space-y-4 mt-8">
          <div class="bg-white border border-gray-200 rounded-2xl p-6 card-hover shadow-sm">
            <i class="fas fa-plane text-3xl text-yellow-600 mb-3 block"></i>
            <h4 class="font-bold text-gray-900 mb-2">Export Management</h4>
            <p class="text-gray-500 text-sm">International trade facilitation to UAE, Europe & beyond</p>
          </div>
          <div class="bg-yellow-500 text-white rounded-2xl p-6 card-hover">
            <i class="fas fa-chart-line text-3xl mb-3 block"></i>
            <h4 class="font-bold mb-2">Quality Assurance</h4>
            <p class="text-yellow-100 text-sm">Rigorous grading for retail & export standards</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Services Section -->
<section id="services" class="bg-white py-24">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="text-center mb-16">
      <div class="inline-block bg-yellow-100 text-yellow-800 px-4 py-2 rounded-full text-sm font-semibold mb-4">Our Services</div>
      <h2 class="text-4xl font-bold text-gray-900 mb-4">Comprehensive Agri-Commerce Solutions</h2>
      <p class="text-gray-500 text-lg max-w-2xl mx-auto">From farm onboarding to international export, we manage every step of the supply chain</p>
    </div>
    <div class="grid md:grid-cols-3 gap-8">
      <div class="bg-gradient-to-br from-green-50 to-green-100 rounded-2xl p-8 card-hover border border-green-200">
        <div class="w-14 h-14 feature-icon rounded-xl flex items-center justify-center mb-6">
          <i class="fas fa-user-check text-white text-xl"></i>
        </div>
        <h3 class="text-xl font-bold text-gray-900 mb-3">Farmer Onboarding</h3>
        <p class="text-gray-600 leading-relaxed mb-4">We identify and recruit unaccredited black farmers with high potential, providing end-to-end support from registration to market readiness.</p>
        <ul class="space-y-2 text-sm text-gray-600">
          <li><i class="fas fa-check text-green-600 mr-2"></i>Digital application process</li>
          <li><i class="fas fa-check text-green-600 mr-2"></i>Document verification</li>
          <li><i class="fas fa-check text-green-600 mr-2"></i>Farm assessment visits</li>
          <li><i class="fas fa-check text-green-600 mr-2"></i>Progress tracking portal</li>
        </ul>
      </div>
      <div class="bg-gradient-to-br from-blue-50 to-blue-100 rounded-2xl p-8 card-hover border border-blue-200">
        <div class="w-14 h-14 bg-blue-700 rounded-xl flex items-center justify-center mb-6">
          <i class="fas fa-certificate text-white text-xl"></i>
        </div>
        <h3 class="text-xl font-bold text-gray-900 mb-3">Accreditation & Compliance</h3>
        <p class="text-gray-600 leading-relaxed mb-4">Full support to achieve internationally recognized certifications required by major retail chains and export markets.</p>
        <ul class="space-y-2 text-sm text-gray-600">
          <li><i class="fas fa-check text-blue-600 mr-2"></i>GAP Certification support</li>
          <li><i class="fas fa-check text-blue-600 mr-2"></i>HACCP implementation</li>
          <li><i class="fas fa-check text-blue-600 mr-2"></i>Food Safety training</li>
          <li><i class="fas fa-check text-blue-600 mr-2"></i>Health & Safety compliance</li>
        </ul>
      </div>
      <div class="bg-gradient-to-br from-yellow-50 to-yellow-100 rounded-2xl p-8 card-hover border border-yellow-200">
        <div class="w-14 h-14 bg-yellow-600 rounded-xl flex items-center justify-center mb-6">
          <i class="fas fa-globe text-white text-xl"></i>
        </div>
        <h3 class="text-xl font-bold text-gray-900 mb-3">Market Access & Export</h3>
        <p class="text-gray-600 leading-relaxed mb-4">Direct connections to South Africa's largest retailers and international export markets across Europe and the Middle East.</p>
        <ul class="space-y-2 text-sm text-gray-600">
          <li><i class="fas fa-check text-yellow-600 mr-2"></i>Retail market linkage</li>
          <li><i class="fas fa-check text-yellow-600 mr-2"></i>Export to UAE, Ireland</li>
          <li><i class="fas fa-check text-yellow-600 mr-2"></i>Turkey & Croatia markets</li>
          <li><i class="fas fa-check text-yellow-600 mr-2"></i>Wholesale aggregation</li>
        </ul>
      </div>
    </div>
  </div>
</section>

<!-- Use Cases Section -->
<section id="use-cases" class="section-gradient py-24">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="text-center mb-16">
      <div class="inline-block bg-green-100 text-green-800 px-4 py-2 rounded-full text-sm font-semibold mb-4">Use Cases</div>
      <h2 class="text-4xl font-bold text-gray-900 mb-4">How KhanyaKhwezi Creates Value</h2>
      <p class="text-gray-500 text-lg max-w-2xl mx-auto">Real business scenarios where our platform makes a measurable difference</p>
    </div>
    <div class="grid lg:grid-cols-3 gap-8">
      <div class="bg-white rounded-2xl overflow-hidden shadow-lg card-hover border border-gray-100">
        <div class="h-3 green-gradient"></div>
        <div class="p-8">
          <div class="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center mb-6">
            <span class="text-2xl">👨‍🌾</span>
          </div>
          <div class="text-xs font-semibold text-green-600 uppercase tracking-wider mb-2">Use Case 1</div>
          <h3 class="text-xl font-bold text-gray-900 mb-4">Small-Scale Farmer to Retail Supplier</h3>
          <p class="text-gray-600 leading-relaxed mb-6">A communal land farmer in KZN growing tomatoes and spinach wants to supply to major retail chains but lacks GAP certification. KhanyaKhwezi handles the entire accreditation process, quality grading, and retail negotiation.</p>
          <div class="space-y-3">
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-green-200 rounded-full flex items-center justify-center text-green-700 font-bold text-sm">1</div>
              <span class="text-sm text-gray-600">Online farmer registration & document upload</span>
            </div>
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-green-200 rounded-full flex items-center justify-center text-green-700 font-bold text-sm">2</div>
              <span class="text-sm text-gray-600">GAP audit & compliance training provided</span>
            </div>
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-green-200 rounded-full flex items-center justify-center text-green-700 font-bold text-sm">3</div>
              <span class="text-sm text-gray-600">First retail order fulfilled within 60 days</span>
            </div>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-2xl overflow-hidden shadow-lg card-hover border border-gray-100">
        <div class="h-3 bg-gradient-to-r from-blue-600 to-blue-800"></div>
        <div class="p-8">
          <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center mb-6">
            <span class="text-2xl">✈️</span>
          </div>
          <div class="text-xs font-semibold text-blue-600 uppercase tracking-wider mb-2">Use Case 2</div>
          <h3 class="text-xl font-bold text-gray-900 mb-4">Export-Ready Avocado & Potato Supplier</h3>
          <p class="text-gray-600 leading-relaxed mb-6">An established farmer in Limpopo with existing GAP certification wants to break into the UAE and European markets for avocados. KhanyaKhwezi manages export compliance, logistics, and buyer relationships.</p>
          <div class="space-y-3">
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-blue-200 rounded-full flex items-center justify-center text-blue-700 font-bold text-sm">1</div>
              <span class="text-sm text-gray-600">Export readiness assessment & HACCP support</span>
            </div>
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-blue-200 rounded-full flex items-center justify-center text-blue-700 font-bold text-sm">2</div>
              <span class="text-sm text-gray-600">Buyer matching in UAE & Irish markets</span>
            </div>
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-blue-200 rounded-full flex items-center justify-center text-blue-700 font-bold text-sm">3</div>
              <span class="text-sm text-gray-600">A-Grade export supply chain established</span>
            </div>
          </div>
        </div>
      </div>
      <div class="bg-white rounded-2xl overflow-hidden shadow-lg card-hover border border-gray-100">
        <div class="h-3 bg-gradient-to-r from-yellow-500 to-yellow-700"></div>
        <div class="p-8">
          <div class="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center mb-6">
            <span class="text-2xl">🏢</span>
          </div>
          <div class="text-xs font-semibold text-yellow-600 uppercase tracking-wider mb-2">Use Case 3</div>
          <h3 class="text-xl font-bold text-gray-900 mb-4">Retail Buyer: Consistent Supply Aggregation</h3>
          <p class="text-gray-600 leading-relaxed mb-6">A major retail chain needs a reliable, compliant source of seasonal fresh produce from verified BEE-compliant farmers. KhanyaKhwezi aggregates supply from multiple accredited farms to meet volume demands.</p>
          <div class="space-y-3">
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-yellow-200 rounded-full flex items-center justify-center text-yellow-700 font-bold text-sm">1</div>
              <span class="text-sm text-gray-600">Vetted network of B-BBEE compliant farmers</span>
            </div>
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-yellow-200 rounded-full flex items-center justify-center text-yellow-700 font-bold text-sm">2</div>
              <span class="text-sm text-gray-600">Consistent quality grading & cold chain</span>
            </div>
            <div class="flex items-center gap-3 bg-gray-50 rounded-lg p-3">
              <div class="w-8 h-8 bg-yellow-200 rounded-full flex items-center justify-center text-yellow-700 font-bold text-sm">3</div>
              <span class="text-sm text-gray-600">Single invoice, multiple farm aggregation</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Value Chain -->
<section class="green-gradient py-20">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 text-center">
    <h2 class="text-3xl font-bold text-white mb-12">Our Value Chain</h2>
    <div class="flex flex-col md:flex-row items-center justify-center gap-4">
      <div class="bg-white/15 backdrop-blur rounded-2xl p-6 text-white text-center w-48">
        <i class="fas fa-tractor text-3xl gold-accent mb-3 block"></i>
        <div class="font-bold">Farmer Sourcing</div>
        <div class="text-green-200 text-xs mt-1">& Production</div>
      </div>
      <i class="fas fa-chevron-right text-white text-2xl hidden md:block gold-accent"></i>
      <div class="bg-white/15 backdrop-blur rounded-2xl p-6 text-white text-center w-48">
        <i class="fas fa-clipboard-check text-3xl gold-accent mb-3 block"></i>
        <div class="font-bold">KKH Compliance</div>
        <div class="text-green-200 text-xs mt-1">& Aggregation</div>
      </div>
      <i class="fas fa-chevron-right text-white text-2xl hidden md:block gold-accent"></i>
      <div class="bg-white/15 backdrop-blur rounded-2xl p-6 text-white text-center w-48">
        <i class="fas fa-store text-3xl gold-accent mb-3 block"></i>
        <div class="font-bold">Market Wholesale</div>
        <div class="text-green-200 text-xs mt-1">& Retail</div>
      </div>
      <i class="fas fa-chevron-right text-white text-2xl hidden md:block gold-accent"></i>
      <div class="bg-white/15 backdrop-blur rounded-2xl p-6 text-white text-center w-48">
        <i class="fas fa-globe text-3xl gold-accent mb-3 block"></i>
        <div class="font-bold">Global Export</div>
        <div class="text-green-200 text-xs mt-1">Distribution</div>
      </div>
    </div>
  </div>
</section>

<!-- Testimonials -->
<section id="testimonials" class="bg-white py-24">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="text-center mb-16">
      <div class="inline-block bg-yellow-100 text-yellow-800 px-4 py-2 rounded-full text-sm font-semibold mb-4">Success Stories</div>
      <h2 class="text-4xl font-bold text-gray-900 mb-4">Farmers Who Found Their Market</h2>
    </div>
    <div class="grid md:grid-cols-3 gap-8">
      <div class="testimonial-card bg-gray-50 rounded-2xl p-8 card-hover">
        <div class="flex items-center gap-1 mb-4">
          ${[1,2,3,4,5].map(() => '<i class="fas fa-star text-yellow-400 text-sm"></i>').join('')}
        </div>
        <p class="text-gray-700 italic leading-relaxed mb-6">"Before KhanyaKhwezi, I was selling my tomatoes at a roadside stall for almost nothing. Now I supply directly to a major retailer in KZN. My income has tripled in one year."</p>
        <div class="flex items-center gap-3">
          <div class="w-12 h-12 rounded-full bg-green-600 flex items-center justify-center text-white font-bold text-xl">S</div>
          <div>
            <div class="font-bold text-gray-900">Sipho Nkosi</div>
            <div class="text-green-600 text-sm">Vegetable Farmer, KwaZulu-Natal</div>
          </div>
        </div>
      </div>
      <div class="testimonial-card bg-gray-50 rounded-2xl p-8 card-hover">
        <div class="flex items-center gap-1 mb-4">
          ${[1,2,3,4,5].map(() => '<i class="fas fa-star text-yellow-400 text-sm"></i>').join('')}
        </div>
        <p class="text-gray-700 italic leading-relaxed mb-6">"The accreditation support was incredible. KhanyaKhwezi helped me get my GAP certificate and connected me with buyers in Ireland for my avocados. I never thought I'd be exporting internationally."</p>
        <div class="flex items-center gap-3">
          <div class="w-12 h-12 rounded-full bg-yellow-600 flex items-center justify-center text-white font-bold text-xl">T</div>
          <div>
            <div class="font-bold text-gray-900">Thandiswa Dlamini</div>
            <div class="text-green-600 text-sm">Avocado & Fruit Farmer, Limpopo</div>
          </div>
        </div>
      </div>
      <div class="testimonial-card bg-gray-50 rounded-2xl p-8 card-hover">
        <div class="flex items-center gap-1 mb-4">
          ${[1,2,3,4,5].map(() => '<i class="fas fa-star text-yellow-400 text-sm"></i>').join('')}
        </div>
        <p class="text-gray-700 italic leading-relaxed mb-6">"As a retail procurement manager, finding consistent, compliant, BEE-certified fresh produce was always a challenge. KhanyaKhwezi has become our most reliable supply partner."</p>
        <div class="flex items-center gap-3">
          <div class="w-12 h-12 rounded-full bg-blue-600 flex items-center justify-center text-white font-bold text-xl">M</div>
          <div>
            <div class="font-bold text-gray-900">Marcus van der Berg</div>
            <div class="text-green-600 text-sm">Procurement Manager, Major Retailer</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</section>

<!-- Farmer CTA -->
<section class="section-gradient py-20">
  <div class="max-w-4xl mx-auto px-4 text-center">
    <div class="bg-white rounded-3xl shadow-xl p-12 border border-gray-100">
      <i class="fas fa-seedling text-5xl text-green-600 mb-6 block"></i>
      <h2 class="text-3xl font-bold text-gray-900 mb-4">Are You a Farmer Looking to Access Markets?</h2>
      <p class="text-gray-600 text-lg mb-8 max-w-2xl mx-auto">Join our Accreditation Support Program and get the tools, training, and market connections you need to grow your farming business. Apply online in minutes.</p>
      <div class="flex flex-col sm:flex-row gap-4 justify-center">
        <a href="/apply" class="bg-green-700 text-white px-8 py-4 rounded-xl font-bold text-lg hover:bg-green-800 transition-colors shadow-lg">
          <i class="fas fa-clipboard-list mr-2"></i>Apply Now — It's Free
        </a>
        <a href="/farmer-portal" class="bg-gray-100 text-gray-700 px-8 py-4 rounded-xl font-semibold text-lg hover:bg-gray-200 transition-colors">
          <i class="fas fa-sign-in-alt mr-2"></i>Farmer Login
        </a>
      </div>
    </div>
  </div>
</section>

<!-- Contact Section -->
<section id="contact" class="bg-gray-900 py-24 text-white">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="grid lg:grid-cols-2 gap-16">
      <div>
        <div class="inline-block bg-green-800 text-green-200 px-4 py-2 rounded-full text-sm font-semibold mb-6">Get In Touch</div>
        <h2 class="text-4xl font-bold mb-6">Request a <span class="gold-accent">Demo</span> or Partner with Us</h2>
        <p class="text-gray-400 text-lg leading-relaxed mb-8">Whether you're a farmer seeking market access, a retailer looking for a reliable supply chain, or an investor interested in sustainable agriculture — we'd love to connect.</p>
        <div class="space-y-4">
          <div class="flex items-center gap-4">
            <div class="w-10 h-10 bg-green-800 rounded-lg flex items-center justify-center"><i class="fas fa-map-marker-alt text-green-400"></i></div>
            <div><div class="text-sm text-gray-400">Address</div><div class="font-medium">KwaDukuza, KwaZulu-Natal, South Africa</div></div>
          </div>
          <div class="flex items-center gap-4">
            <div class="w-10 h-10 bg-green-800 rounded-lg flex items-center justify-center"><i class="fas fa-phone text-green-400"></i></div>
            <div><div class="text-sm text-gray-400">Phone</div><div class="font-medium">+27 31 005 3803</div></div>
          </div>
          <div class="flex items-center gap-4">
            <div class="w-10 h-10 bg-green-800 rounded-lg flex items-center justify-center"><i class="fas fa-envelope text-green-400"></i></div>
            <div><div class="text-sm text-gray-400">Email</div><div class="font-medium">info@khanyakhwezi.co.za</div></div>
          </div>
          <div class="flex items-center gap-4">
            <div class="w-10 h-10 bg-green-800 rounded-lg flex items-center justify-center"><i class="fas fa-globe text-green-400"></i></div>
            <div><div class="text-sm text-gray-400">Website</div><div class="font-medium">www.khanyakhwezi.co.za</div></div>
          </div>
        </div>
      </div>
      <div>
        <form id="demoForm" class="bg-gray-800 rounded-2xl p-8 space-y-4">
          <h3 class="text-xl font-bold mb-2">Request a Demo</h3>
          <div class="grid grid-cols-2 gap-4">
            <input type="text" id="demoName" placeholder="Full Name" class="bg-gray-700 text-white rounded-lg px-4 py-3 w-full placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-green-500">
            <input type="email" id="demoEmail" placeholder="Email Address" class="bg-gray-700 text-white rounded-lg px-4 py-3 w-full placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-green-500">
          </div>
          <input type="text" id="demoCompany" placeholder="Company / Farm Name" class="bg-gray-700 text-white rounded-lg px-4 py-3 w-full placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-green-500">
          <select id="demoType" class="bg-gray-700 text-white rounded-lg px-4 py-3 w-full focus:outline-none focus:ring-2 focus:ring-green-500">
            <option value="">I am a...</option>
            <option>Farmer seeking market access</option>
            <option>Retailer seeking supply</option>
            <option>Export buyer</option>
            <option>Investor / Partner</option>
          </select>
          <textarea id="demoMessage" rows="4" placeholder="Tell us about your needs..." class="bg-gray-700 text-white rounded-lg px-4 py-3 w-full placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-green-500 resize-none"></textarea>
          <button type="submit" class="gold-bg w-full text-white py-4 rounded-xl font-bold text-lg hover:opacity-90 transition-opacity">
            <i class="fas fa-paper-plane mr-2"></i>Send Request
          </button>
          <div id="demoSuccess" class="hidden bg-green-800 text-green-200 rounded-lg p-4 text-center">
            <i class="fas fa-check-circle mr-2"></i>Thank you! We'll be in touch within 24 hours.
          </div>
        </form>
      </div>
    </div>
  </div>
</section>

<!-- Footer -->
<footer class="bg-gray-950 text-gray-400 py-12">
  <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
    <div class="grid md:grid-cols-4 gap-8 mb-8">
      <div class="md:col-span-2">
        <div class="flex items-center space-x-3 mb-4">
          ${kkhLogoHTML(40)}
          <div>
            <span class="font-bold text-white text-lg block leading-tight">KhanyaKhwezi</span>
            <span class="text-xs text-green-500 font-medium tracking-wide">HARVESTING</span>
          </div>
        </div>
        <p class="text-sm leading-relaxed max-w-xs">Empowering African farmers through market access, compliance support, and sustainable supply chain solutions.</p>
      </div>
      <div>
        <h4 class="text-white font-semibold mb-4">Quick Links</h4>
        <ul class="space-y-2 text-sm">
          <li><a href="#about" class="hover:text-white transition-colors">About Us</a></li>
          <li><a href="#services" class="hover:text-white transition-colors">Services</a></li>
          <li><a href="/apply" class="hover:text-white transition-colors">Apply as Farmer</a></li>
          <li><a href="/farmer-portal" class="hover:text-white transition-colors">Farmer Portal</a></li>
          <li><a href="/admin" class="hover:text-white transition-colors">Admin Login</a></li>
        </ul>
      </div>
      <div>
        <h4 class="text-white font-semibold mb-4">Contact</h4>
        <ul class="space-y-2 text-sm">
          <li><i class="fas fa-phone mr-2 text-green-500"></i>+27 31 005 3803</li>
          <li><i class="fas fa-envelope mr-2 text-green-500"></i>info@khanyakhwezi.co.za</li>
          <li><i class="fas fa-map-marker-alt mr-2 text-green-500"></i>KwaDukuza, KZN, SA</li>
        </ul>
        <div class="flex space-x-3 mt-4">
          <a href="#" class="w-9 h-9 bg-gray-800 rounded-lg flex items-center justify-center hover:bg-green-700 transition-colors"><i class="fab fa-facebook-f text-sm"></i></a>
          <a href="#" class="w-9 h-9 bg-gray-800 rounded-lg flex items-center justify-center hover:bg-green-700 transition-colors"><i class="fab fa-linkedin-in text-sm"></i></a>
          <a href="#" class="w-9 h-9 bg-gray-800 rounded-lg flex items-center justify-center hover:bg-green-700 transition-colors"><i class="fab fa-whatsapp text-sm"></i></a>
        </div>
      </div>
    </div>
    <div class="border-t border-gray-800 pt-6 flex flex-col md:flex-row justify-between items-center text-sm">
      <p>© 2024 KhanyaKhwezi Harvesting. All rights reserved.</p>
      <div class="flex gap-6 mt-3 md:mt-0">
        <a href="#" class="hover:text-white transition-colors">Privacy Policy</a>
        <a href="#" class="hover:text-white transition-colors">Terms of Service</a>
        <a href="#" class="hover:text-white transition-colors">Cookie Policy</a>
      </div>
    </div>
  </div>
</footer>

<script>
// Mobile menu toggle
document.getElementById('mobileMenuBtn').addEventListener('click', () => {
  document.getElementById('mobileMenu').classList.toggle('hidden');
});

// Smooth scroll
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
  anchor.addEventListener('click', function(e) {
    e.preventDefault();
    const target = document.querySelector(this.getAttribute('href'));
    if (target) target.scrollIntoView({ behavior: 'smooth', block: 'start' });
    document.getElementById('mobileMenu').classList.add('hidden');
  });
});

// Demo form
document.getElementById('demoForm').addEventListener('submit', function(e) {
  e.preventDefault();
  document.getElementById('demoSuccess').classList.remove('hidden');
  this.querySelectorAll('input, select, textarea').forEach(el => el.value = '');
  setTimeout(() => document.getElementById('demoSuccess').classList.add('hidden'), 5000);
});
</script>
</body>
</html>`
}

function farmerPortalHTML() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Farmer Portal — KhanyaKhwezi Harvesting</title>
<link rel="icon" href="/kkh-logo.png">
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
  body { font-family: 'Inter', sans-serif; }
  .green-gradient { background: linear-gradient(135deg, #1a4731 0%, #2d6a4f 100%); }
  .gold-accent { color: #c9a84c; }
  .gold-bg { background: #c9a84c; }
  .progress-fill { transition: width 0.8s ease; }
  .status-pending { background: #fef3c7; color: #92400e; }
  .status-submitted { background: #dbeafe; color: #1e40af; }
  .status-approved { background: #dcfce7; color: #166534; }
  .status-rejected { background: #fee2e2; color: #991b1b; }
</style>
</head>
<body class="bg-gray-50 min-h-screen">

<!-- Header -->
<nav class="green-gradient shadow-lg">
  <div class="max-w-6xl mx-auto px-4 py-4 flex justify-between items-center">
    <a href="/" class="flex items-center space-x-3">
      ${kkhLogoHTML(42)}
      <div>
        <span class="font-bold text-white block leading-tight">KhanyaKhwezi</span>
        <span class="text-xs text-green-200">FARMER PORTAL</span>
      </div>
    </a>
    <div id="authButtons" class="flex gap-3">
      <a href="/apply" class="bg-yellow-500 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-yellow-600 transition-colors">Apply Now</a>
    </div>
    <div id="userMenu" class="hidden flex items-center gap-3">
      <span id="userGreeting" class="text-white text-sm font-medium"></span>
      <button onclick="logout()" class="bg-red-600 text-white px-3 py-2 rounded-lg text-sm hover:bg-red-700 transition-colors">Logout</button>
    </div>
  </div>
</nav>

<!-- Main Content -->
<div class="max-w-6xl mx-auto px-4 py-8">

  <!-- Login Panel -->
  <div id="loginPanel">
    <div class="grid lg:grid-cols-2 gap-12 items-center min-h-[70vh]">
      <div>
        <!-- Logo Featured -->
        <div class="flex items-center gap-4 mb-6">
          <div style="width:80px;height:80px;flex-shrink:0;">
            ${kkhLogoSVG(80)}
          </div>
          <div>
            <div class="text-xl font-black text-gray-900 leading-tight">KhanyaKhwezi</div>
            <div class="text-green-700 text-sm font-bold tracking-widest uppercase">Harvesting</div>
            <div class="text-gray-400 text-xs italic">From the Soil to the Shelf</div>
          </div>
        </div>
        <div class="inline-block bg-green-100 text-green-800 px-4 py-2 rounded-full text-sm font-semibold mb-4">Farmer Portal</div>
        <h1 class="text-4xl font-bold text-gray-900 mb-4">Welcome Back, <span class="text-green-700">Farmer</span></h1>
        <p class="text-gray-600 text-lg leading-relaxed mb-8">Login to continue your application, track your accreditation status, and access your market linkage dashboard.</p>
        <div class="grid grid-cols-2 gap-4">
          <div class="bg-green-50 border border-green-200 rounded-xl p-4 text-center">
            <i class="fas fa-clipboard-list text-2xl text-green-700 mb-2 block"></i>
            <div class="text-sm font-semibold text-gray-800">Save Progress</div>
            <div class="text-xs text-gray-500 mt-1">Continue where you left off</div>
          </div>
          <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-4 text-center">
            <i class="fas fa-upload text-2xl text-yellow-700 mb-2 block"></i>
            <div class="text-sm font-semibold text-gray-800">Upload Docs</div>
            <div class="text-xs text-gray-500 mt-1">Manage your documents</div>
          </div>
          <div class="bg-blue-50 border border-blue-200 rounded-xl p-4 text-center">
            <i class="fas fa-chart-line text-2xl text-blue-700 mb-2 block"></i>
            <div class="text-sm font-semibold text-gray-800">Track Status</div>
            <div class="text-xs text-gray-500 mt-1">Application progress</div>
          </div>
          <div class="bg-purple-50 border border-purple-200 rounded-xl p-4 text-center">
            <i class="fas fa-handshake text-2xl text-purple-700 mb-2 block"></i>
            <div class="text-sm font-semibold text-gray-800">Market Links</div>
            <div class="text-xs text-gray-500 mt-1">Buyer connections</div>
          </div>
        </div>
      </div>

      <div class="bg-white rounded-2xl shadow-xl border border-gray-100 p-8">
        <!-- Tab Switcher -->
        <div class="flex rounded-xl bg-gray-100 p-1 mb-6">
          <button onclick="switchTab('login')" id="loginTabBtn" class="flex-1 py-2.5 rounded-lg text-sm font-semibold transition-all bg-white text-gray-900 shadow">Login</button>
          <button onclick="switchTab('register')" id="registerTabBtn" class="flex-1 py-2.5 rounded-lg text-sm font-semibold transition-all text-gray-500">New Application</button>
        </div>

        <!-- Login Form -->
        <div id="loginForm">
          <h3 class="text-xl font-bold text-gray-900 mb-6">Sign In to Your Account</h3>
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Farmer ID</label>
              <input type="text" id="loginFarmerID" placeholder="e.g. KKH-2024-1234" class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-green-500 font-mono">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Password</label>
              <div class="relative">
                <input type="password" id="loginPassword" placeholder="Enter your password" class="w-full border border-gray-300 rounded-lg px-4 py-3 pr-12 focus:outline-none focus:ring-2 focus:ring-green-500">
                <button type="button" onclick="togglePass('loginPassword')" class="absolute right-3 top-1/2 -translate-y-1/2 text-gray-400 hover:text-gray-600">
                  <i class="fas fa-eye"></i>
                </button>
              </div>
            </div>
            <div id="loginError" class="hidden bg-red-50 border border-red-200 text-red-700 rounded-lg p-3 text-sm"></div>
            <button onclick="doLogin()" class="w-full bg-green-700 text-white py-3 rounded-lg font-bold hover:bg-green-800 transition-colors">
              <i class="fas fa-sign-in-alt mr-2"></i>Login to Portal
            </button>
          </div>
          <p class="text-center text-gray-500 text-sm mt-4">Don't have an account? <button onclick="switchTab('register')" class="text-green-700 font-semibold">Apply Now</button></p>
          
          <!-- Demo credentials -->
          <div class="mt-4 bg-yellow-50 border border-yellow-200 rounded-lg p-3">
            <p class="text-xs text-yellow-800 font-medium mb-1">📋 Demo Credentials (load demo data first from admin):</p>
            <p class="text-xs text-yellow-700">ID: <code class="bg-yellow-100 px-1 rounded">KKH-2024-1001</code> | Pass: <code class="bg-yellow-100 px-1 rounded">Pass1234</code></p>
          </div>
        </div>

        <!-- Register Form -->
        <div id="registerForm" class="hidden">
          <h3 class="text-xl font-bold text-gray-900 mb-2">Create Your Application</h3>
          <p class="text-gray-500 text-sm mb-6">We'll create your account and send your unique login credentials.</p>
          <div class="space-y-4">
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Full Name *</label>
              <input type="text" id="regName" placeholder="Enter your full name" class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-green-500">
            </div>
            <div>
              <label class="block text-sm font-medium text-gray-700 mb-1">Email Address *</label>
              <input type="email" id="regEmail" placeholder="your@email.com" class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-green-500">
            </div>
            <div id="regError" class="hidden bg-red-50 border border-red-200 text-red-700 rounded-lg p-3 text-sm"></div>
            <button onclick="doRegister()" class="w-full gold-bg text-white py-3 rounded-lg font-bold hover:opacity-90 transition-opacity">
              <i class="fas fa-user-plus mr-2"></i>Create My Account
            </button>
          </div>
          <p class="text-center text-gray-500 text-sm mt-4">Already have an account? <button onclick="switchTab('login')" class="text-green-700 font-semibold">Login here</button></p>
        </div>

        <!-- Credentials Display -->
        <div id="credentialsDisplay" class="hidden">
          <div class="bg-green-50 border-2 border-green-400 rounded-xl p-6 text-center">
            <i class="fas fa-check-circle text-4xl text-green-600 mb-3 block"></i>
            <h3 class="font-bold text-gray-900 text-lg mb-3">Account Created Successfully!</h3>
            <p class="text-gray-600 text-sm mb-4">Please save your login credentials below. You'll need these to continue your application.</p>
            <div class="bg-white rounded-lg p-4 border border-green-300 text-left space-y-2 mb-4">
              <div class="flex justify-between items-center">
                <span class="text-sm text-gray-500">Farmer ID:</span>
                <span id="credFarmerID" class="font-mono font-bold text-green-700 bg-green-100 px-2 py-1 rounded"></span>
              </div>
              <div class="flex justify-between items-center">
                <span class="text-sm text-gray-500">Password:</span>
                <span id="credPassword" class="font-mono font-bold text-blue-700 bg-blue-100 px-2 py-1 rounded"></span>
              </div>
            </div>
            <p class="text-xs text-red-600 mb-4"><i class="fas fa-exclamation-triangle mr-1"></i>Save these credentials — you will need them to login</p>
            <button onclick="continueToApplication()" class="w-full bg-green-700 text-white py-3 rounded-lg font-bold hover:bg-green-800 transition-colors">
              Continue to Application Form <i class="fas fa-arrow-right ml-2"></i>
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- Dashboard Panel (shown after login) -->
  <div id="dashboardPanel" class="hidden">
    <!-- Progress Overview -->
    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 mb-6">
      <div class="flex flex-col md:flex-row items-start md:items-center justify-between gap-4">
        <div>
          <h2 id="dashGreeting" class="text-2xl font-bold text-gray-900"></h2>
          <p id="dashFarmerID" class="text-gray-500 text-sm font-mono mt-1"></p>
        </div>
        <div class="flex gap-3">
          <span id="dashStatus" class="px-4 py-2 rounded-full text-sm font-semibold"></span>
          <a href="/apply" id="continueAppBtn" class="bg-green-700 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-green-800 transition-colors">
            <i class="fas fa-edit mr-1"></i>Continue Application
          </a>
        </div>
      </div>
      <div class="mt-6">
        <div class="flex justify-between items-center mb-2">
          <span class="text-sm font-semibold text-gray-700">Application Progress</span>
          <span id="progressPercent" class="text-sm font-bold text-green-700"></span>
        </div>
        <div class="h-3 bg-gray-100 rounded-full overflow-hidden">
          <div id="progressBar" class="h-full bg-gradient-to-r from-green-500 to-green-600 rounded-full progress-fill" style="width:0%"></div>
        </div>
        <div class="mt-3 flex flex-wrap gap-2" id="completedSections"></div>
      </div>
    </div>

    <!-- Quick Actions -->
    <div class="grid md:grid-cols-3 gap-4 mb-6">
      <a href="/apply" class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 hover:shadow-md transition-shadow flex items-center gap-4">
        <div class="w-12 h-12 bg-green-100 rounded-xl flex items-center justify-center">
          <i class="fas fa-clipboard-list text-green-700 text-xl"></i>
        </div>
        <div>
          <div class="font-semibold text-gray-900">Application Form</div>
          <div class="text-xs text-gray-500">Continue filling in your details</div>
        </div>
      </a>
      <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 hover:shadow-md transition-shadow flex items-center gap-4 cursor-pointer" onclick="alert('Document upload: Please upload via email to info@khanyakhwezi.co.za with your Farmer ID as reference. Full upload system coming soon.')">
        <div class="w-12 h-12 bg-blue-100 rounded-xl flex items-center justify-center">
          <i class="fas fa-upload text-blue-700 text-xl"></i>
        </div>
        <div>
          <div class="font-semibold text-gray-900">Upload Documents</div>
          <div class="text-xs text-gray-500">Submit your required files</div>
        </div>
      </div>
      <div class="bg-white rounded-xl border border-gray-100 shadow-sm p-5 hover:shadow-md transition-shadow flex items-center gap-4 cursor-pointer" onclick="alert('Our team will contact you regarding market linkage opportunities once your application is approved.')">
        <div class="w-12 h-12 bg-yellow-100 rounded-xl flex items-center justify-center">
          <i class="fas fa-handshake text-yellow-700 text-xl"></i>
        </div>
        <div>
          <div class="font-semibold text-gray-900">Market Linkage</div>
          <div class="text-xs text-gray-500">Connect with buyers</div>
        </div>
      </div>
    </div>

    <!-- Document Checklist -->
    <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
      <h3 class="text-lg font-bold text-gray-900 mb-4">Required Documents Checklist</h3>
      <div class="grid md:grid-cols-2 gap-3">
        ${[
          ['Personal Documents', ['Copy of ID Document', 'Proof of Residence (≤3 months old)']],
          ['Farm/Land Documents', ['Proof of Land Ownership / Title Deed', 'Lease Agreement (if applicable)', 'Tribal Authority Letter (if communal)', 'Farm Photos (optional)']],
          ['Business & Financial', ['Bank Confirmation Letter / Statement', 'Company Registration Certificate', 'Tax Clearance Certificate', 'B-BBEE Certificate']],
          ['Certification Documents', ['GAP Certificate (if held)', 'HACCP Certificate (if held)', 'Food Safety Certificate (if held)', 'Training Certificates (if any)']]
        ].map(([category, docs]) => `
        <div>
          <h4 class="text-sm font-semibold text-gray-700 mb-2">${category}</h4>
          <ul class="space-y-1">
            ${(docs as string[]).map(doc => `<li class="flex items-center gap-2 text-sm text-gray-600"><i class="fas fa-circle text-gray-300 text-xs"></i>${doc}</li>`).join('')}
          </ul>
        </div>`).join('')}
      </div>
      <div class="mt-4 bg-blue-50 border border-blue-200 rounded-lg p-3">
        <p class="text-sm text-blue-800"><i class="fas fa-info-circle mr-2"></i>Email your documents to <strong>info@khanyakhwezi.co.za</strong> with your Farmer ID in the subject line.</p>
      </div>
    </div>
  </div>
</div>

<script>
let currentToken = localStorage.getItem('kkhToken');
let currentFarmerID = localStorage.getItem('kkhFarmerID');
let tempCredentials = null;

function switchTab(tab) {
  const loginForm = document.getElementById('loginForm');
  const registerForm = document.getElementById('registerForm');
  const credDisplay = document.getElementById('credentialsDisplay');
  const loginBtn = document.getElementById('loginTabBtn');
  const regBtn = document.getElementById('registerTabBtn');
  
  if (tab === 'login') {
    loginForm.classList.remove('hidden'); registerForm.classList.add('hidden'); credDisplay.classList.add('hidden');
    loginBtn.classList.add('bg-white', 'text-gray-900', 'shadow'); loginBtn.classList.remove('text-gray-500');
    regBtn.classList.remove('bg-white', 'text-gray-900', 'shadow'); regBtn.classList.add('text-gray-500');
  } else {
    loginForm.classList.add('hidden'); registerForm.classList.remove('hidden'); credDisplay.classList.add('hidden');
    regBtn.classList.add('bg-white', 'text-gray-900', 'shadow'); regBtn.classList.remove('text-gray-500');
    loginBtn.classList.remove('bg-white', 'text-gray-900', 'shadow'); loginBtn.classList.add('text-gray-500');
  }
}

function togglePass(id) {
  const el = document.getElementById(id);
  el.type = el.type === 'password' ? 'text' : 'password';
}

async function doLogin() {
  const farmerID = document.getElementById('loginFarmerID').value.trim();
  const password = document.getElementById('loginPassword').value;
  const errEl = document.getElementById('loginError');
  
  if (!farmerID || !password) { errEl.textContent = 'Please enter your Farmer ID and password.'; errEl.classList.remove('hidden'); return; }
  
  try {
    const res = await fetch('/api/login', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({farmerID, password}) });
    const data = await res.json();
    if (data.success) {
      localStorage.setItem('kkhToken', data.sessionToken);
      localStorage.setItem('kkhFarmerID', data.farmerID);
      showDashboard(data);
    } else {
      errEl.textContent = data.message; errEl.classList.remove('hidden');
    }
  } catch(e) { errEl.textContent = 'Connection error. Please try again.'; errEl.classList.remove('hidden'); }
}

async function doRegister() {
  const fullName = document.getElementById('regName').value.trim();
  const email = document.getElementById('regEmail').value.trim();
  const errEl = document.getElementById('regError');
  
  if (!fullName || !email) { errEl.textContent = 'Full name and email are required.'; errEl.classList.remove('hidden'); return; }
  
  try {
    const res = await fetch('/api/register', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({email, fullName}) });
    const data = await res.json();
    if (data.success) {
      tempCredentials = { farmerID: data.farmerID, password: data.password };
      document.getElementById('credFarmerID').textContent = data.farmerID;
      document.getElementById('credPassword').textContent = data.password;
      document.getElementById('registerForm').classList.add('hidden');
      document.getElementById('credentialsDisplay').classList.remove('hidden');
    } else {
      errEl.textContent = data.message; errEl.classList.remove('hidden');
    }
  } catch(e) { errEl.textContent = 'Registration failed. Please try again.'; errEl.classList.remove('hidden'); }
}

function continueToApplication() {
  if (tempCredentials) {
    localStorage.setItem('kkhPendingLogin', JSON.stringify(tempCredentials));
    window.location.href = '/apply';
  }
}

function showDashboard(data) {
  document.getElementById('loginPanel').classList.add('hidden');
  document.getElementById('dashboardPanel').classList.remove('hidden');
  document.getElementById('authButtons').classList.add('hidden');
  document.getElementById('userMenu').classList.remove('hidden');
  document.getElementById('userGreeting').textContent = data.fullName || data.farmerID;
  
  document.getElementById('dashGreeting').textContent = 'Welcome, ' + (data.fullName || data.farmerID) + '!';
  document.getElementById('dashFarmerID').textContent = 'Farmer ID: ' + data.farmerID;
  
  const statusEl = document.getElementById('dashStatus');
  const status = data.status || 'pending';
  statusEl.textContent = status.charAt(0).toUpperCase() + status.slice(1);
  statusEl.className = 'px-4 py-2 rounded-full text-sm font-semibold status-' + status;
  
  const prog = data.progress || 0;
  document.getElementById('progressPercent').textContent = prog + '% Complete';
  setTimeout(() => { document.getElementById('progressBar').style.width = prog + '%'; }, 100);
  
  const sections = data.completedSections || [];
  const secContainer = document.getElementById('completedSections');
  const sectionNames = {A:'Personal Info', B:'Farm Info', C:'Production', D:'Accreditation', E:'Business', F:'Support Needed', G:'References', H:'Declaration'};
  secContainer.innerHTML = Object.entries(sectionNames).map(([k,v]) => 
    \`<span class="px-3 py-1 rounded-full text-xs font-medium \${sections.includes(k) ? 'bg-green-100 text-green-800' : 'bg-gray-100 text-gray-500'}">\${sections.includes(k) ? '✓ ' : ''}\${v}</span>\`
  ).join('');
}

function logout() {
  localStorage.removeItem('kkhToken');
  localStorage.removeItem('kkhFarmerID');
  window.location.reload();
}

// Auto-login if token exists
async function checkAuth() {
  if (currentToken && currentFarmerID) {
    try {
      const res = await fetch('/api/farmer/profile', { headers: {'Authorization': 'Bearer ' + currentToken} });
      const data = await res.json();
      if (data.success) showDashboard({...data.farmer, sessionToken: currentToken});
    } catch(e) { localStorage.removeItem('kkhToken'); }
  }
}
checkAuth();
</script>
</body>
</html>`
}

function applicationFormHTML() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Farmer Application — KhanyaKhwezi Harvesting</title>
<link rel="icon" href="/kkh-logo.png">
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<style>
  body { font-family: 'Inter', sans-serif; }
  .green-gradient { background: linear-gradient(135deg, #1a4731 0%, #2d6a4f 100%); }
  .gold-bg { background: #c9a84c; }
  .section-tab { transition: all 0.2s; cursor: pointer; }
  .section-tab.active { background: white; color: #166534; font-weight: 700; box-shadow: 0 2px 8px rgba(0,0,0,0.1); }
  .section-panel { display: none; }
  .section-panel.active { display: block; }
  .field-label { font-size: 0.875rem; font-weight: 500; color: #374151; margin-bottom: 0.375rem; display: block; }
  .field-input { width: 100%; border: 1px solid #d1d5db; border-radius: 0.5rem; padding: 0.75rem 1rem; font-size: 0.9rem; transition: all 0.2s; }
  .field-input:focus { outline: none; border-color: #16a34a; box-shadow: 0 0 0 3px rgba(22,163,74,0.1); }
  .checkbox-item { display: flex; align-items: center; gap: 0.5rem; cursor: pointer; }
  .checkbox-item input { width: 1rem; height: 1rem; accent-color: #16a34a; }
  .progress-step { transition: all 0.3s; }
  .save-toast { position: fixed; bottom: 20px; right: 20px; background: #166534; color: white; padding: 12px 20px; border-radius: 12px; font-size: 0.875rem; font-weight: 600; z-index: 100; transform: translateY(80px); transition: transform 0.3s; }
  .save-toast.show { transform: translateY(0); }
</style>
</head>
<body class="bg-gray-50 min-h-screen">

<div class="save-toast" id="saveToast"><i class="fas fa-check mr-2"></i>Progress saved!</div>

<!-- Header -->
<nav class="green-gradient shadow-lg sticky top-0 z-50">
  <div class="max-w-5xl mx-auto px-4 py-4 flex justify-between items-center">
    <a href="/" class="flex items-center space-x-3">
      ${kkhLogoHTML(42)}
      <div>
        <span class="font-bold text-white block leading-tight">KhanyaKhwezi</span>
        <span class="text-xs text-green-200">ACCREDITATION APPLICATION</span>
      </div>
    </a>
    <div class="flex items-center gap-3">
      <span id="navFarmerID" class="text-green-200 text-xs font-mono hidden"></span>
      <button onclick="saveProgress()" class="bg-white/20 text-white px-3 py-2 rounded-lg text-sm font-medium hover:bg-white/30 transition-colors">
        <i class="fas fa-save mr-1"></i>Save Progress
      </button>
      <a href="/farmer-portal" class="text-green-200 text-sm hover:text-white">Portal</a>
    </div>
  </div>
</nav>

<!-- Auth Gate -->
<div id="authGate" class="max-w-2xl mx-auto px-4 py-16 text-center">
  <div class="bg-white rounded-2xl shadow-xl p-10 border border-gray-100">
    <div class="flex justify-center mb-4">
      <div style="width:90px;height:90px;">
        ${kkhLogoSVG(90)}
      </div>
    </div>
    <div class="text-lg font-black text-gray-900 mb-1">KhanyaKhwezi Harvesting</div>
    <div class="text-green-700 text-xs font-bold tracking-widest uppercase mb-4">Accreditation Support Program</div>
    <i class="fas fa-lock text-3xl text-green-600 mb-3 block"></i>
    <h2 class="text-2xl font-bold text-gray-900 mb-2">Login Required</h2>
    <p class="text-gray-500 mb-6">Please login or create an account to save your application progress</p>
    <div class="space-y-3">
      <div>
        <label class="field-label">Farmer ID</label>
        <input type="text" id="gateID" placeholder="e.g. KKH-2024-1234" class="field-input font-mono">
      </div>
      <div>
        <label class="field-label">Password</label>
        <input type="password" id="gatePass" placeholder="Your password" class="field-input">
      </div>
      <div id="gateError" class="hidden bg-red-50 border border-red-200 text-red-700 rounded-lg p-3 text-sm"></div>
      <button onclick="gateLogin()" class="w-full bg-green-700 text-white py-3 rounded-lg font-bold hover:bg-green-800 transition-colors">Login & Continue</button>
      <p class="text-gray-500 text-sm">No account yet? <a href="/farmer-portal" class="text-green-700 font-semibold">Create one here</a></p>
      <button onclick="continueAsGuest()" class="w-full bg-gray-100 text-gray-600 py-3 rounded-lg font-medium hover:bg-gray-200 transition-colors text-sm">Continue without saving (Guest mode)</button>
    </div>
  </div>
</div>

<!-- Application Form -->
<div id="applicationForm" class="hidden max-w-5xl mx-auto px-4 py-8">
  
  <!-- Progress Header -->
  <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-6 mb-6">
    <div class="flex flex-col md:flex-row md:items-center justify-between gap-4 mb-4">
      <div class="flex items-center gap-4">
        <div style="width:54px;height:54px;flex-shrink:0;">
          ${kkhLogoSVG(54)}
        </div>
        <div>
          <h1 class="text-2xl font-bold text-gray-900">Farmer Onboarding Application</h1>
          <p class="text-gray-500 text-sm mt-0.5">KhanyaKhwezi Accreditation Support Program — Ref: <span id="appFarmerID" class="font-mono text-green-700 font-semibold"></span></p>
        </div>
      </div>
      <div class="text-right">
        <div class="text-2xl font-bold text-green-700" id="progressDisplay">0%</div>
        <div class="text-gray-500 text-xs">Completed</div>
      </div>
    </div>
    <div class="h-2 bg-gray-100 rounded-full overflow-hidden">
      <div id="formProgressBar" class="h-full bg-gradient-to-r from-green-500 to-green-600 rounded-full transition-all duration-500" style="width:0%"></div>
    </div>
    
    <!-- Section Tabs -->
    <div class="flex flex-wrap gap-2 mt-4">
      ${['A','B','C','D','E','F','G','H'].map((s, i) => {
        const names: Record<string, string> = {A:'Personal',B:'Farm',C:'Production',D:'Accreditation',E:'Business',F:'Support',G:'References',H:'Declaration'};
        return `<button onclick="goToSection('${s}')" id="tab${s}" class="section-tab px-3 py-1.5 rounded-lg text-xs font-medium text-gray-500 bg-gray-100 ${i===0?'active':''}">${s}: ${names[s]}</button>`;
      }).join('')}
    </div>
  </div>

  <!-- SECTION A: Personal Information -->
  <div id="sectionA" class="section-panel active bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-green-100 rounded-xl flex items-center justify-center"><span class="font-bold text-green-700">A</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section A: Personal Information</h2><p class="text-gray-500 text-sm">Your personal identification details</p></div>
    </div>
    <div class="grid md:grid-cols-2 gap-5">
      <div class="md:col-span-2">
        <label class="field-label">Full Name (First Name, Surname) *</label>
        <input type="text" id="sA_fullName" class="field-input" placeholder="e.g. Sipho Nkosi">
      </div>
      <div>
        <label class="field-label">ID Number *</label>
        <input type="text" id="sA_idNumber" class="field-input" placeholder="13-digit SA ID Number">
      </div>
      <div>
        <label class="field-label">Date of Birth</label>
        <input type="date" id="sA_dob" class="field-input">
      </div>
      <div>
        <label class="field-label">Gender *</label>
        <select id="sA_gender" class="field-input">
          <option value="">Select gender</option>
          <option>Male</option><option>Female</option><option>Non-binary</option><option>Prefer not to say</option>
        </select>
      </div>
      <div>
        <label class="field-label">Primary Contact Number *</label>
        <input type="tel" id="sA_primaryContact" class="field-input" placeholder="+27 XX XXX XXXX">
      </div>
      <div>
        <label class="field-label">Alternative Contact Number</label>
        <input type="tel" id="sA_altContact" class="field-input" placeholder="+27 XX XXX XXXX">
      </div>
      <div>
        <label class="field-label">Email Address *</label>
        <input type="email" id="sA_email" class="field-input" placeholder="your@email.com">
      </div>
      <div class="md:col-span-2">
        <label class="field-label">Physical Address (Street, Town/City, Province, Postal Code) *</label>
        <textarea id="sA_address" class="field-input" rows="3" placeholder="Enter your full physical address"></textarea>
      </div>
    </div>
    <div class="flex justify-end mt-6">
      <button onclick="nextSection('A','B')" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Next: Farm Information <i class="fas fa-arrow-right ml-2"></i></button>
    </div>
  </div>

  <!-- SECTION B: Farm Information -->
  <div id="sectionB" class="section-panel bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center"><span class="font-bold text-blue-700">B</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section B: Farm Information</h2><p class="text-gray-500 text-sm">Details about your farm and property</p></div>
    </div>
    <div class="grid md:grid-cols-2 gap-5">
      <div>
        <label class="field-label">Farm Name (if applicable)</label>
        <input type="text" id="sB_farmName" class="field-input" placeholder="e.g. Nkosi Family Farm">
      </div>
      <div>
        <label class="field-label">Farm Location / Address *</label>
        <input type="text" id="sB_farmLocation" class="field-input" placeholder="Town/City, Province">
      </div>
      <div>
        <label class="field-label">GPS Coordinates (if known)</label>
        <input type="text" id="sB_gps" class="field-input" placeholder="e.g. -29.1234, 31.5678">
      </div>
      <div>
        <label class="field-label">Years of Farming Experience *</label>
        <select id="sB_yearsExp" class="field-input">
          <option value="">Select range</option>
          <option>Less than 1 year</option><option>1-3 years</option><option>3-5 years</option>
          <option>5-10 years</option><option>More than 10 years</option>
        </select>
      </div>
      <div>
        <label class="field-label">Land Ownership Status *</label>
        <select id="sB_landOwnership" class="field-input">
          <option value="">Select status</option>
          <option>Owned</option><option>Leased</option><option>Communal/Tribal</option><option>Other</option>
        </select>
      </div>
      <div>
        <label class="field-label">Current Water Source *</label>
        <select id="sB_waterSource" class="field-input">
          <option value="">Select source</option>
          <option>Borehole</option><option>Municipal</option><option>River</option><option>Rain-fed</option><option>Multiple Sources</option>
        </select>
      </div>
      <div>
        <label class="field-label">Irrigation System Installed?</label>
        <select id="sB_irrigation" class="field-input">
          <option value="">Select</option>
          <option>Yes</option><option>No</option><option>Partially</option>
        </select>
      </div>
      <div>
        <label class="field-label">Irrigation Type (if applicable)</label>
        <input type="text" id="sB_irrigationType" class="field-input" placeholder="e.g. Drip, Overhead, Furrow">
      </div>
      <div>
        <label class="field-label">Total Farm Size</label>
        <input type="text" id="sB_farmSize" class="field-input" placeholder="e.g. 5 hectares">
      </div>
      <div>
        <label class="field-label">Province *</label>
        <select id="sB_province" class="field-input">
          <option value="">Select province</option>
          <option>KwaZulu-Natal</option><option>Gauteng</option><option>Western Cape</option><option>Eastern Cape</option>
          <option>Limpopo</option><option>Mpumalanga</option><option>North West</option><option>Free State</option><option>Northern Cape</option>
        </select>
      </div>
    </div>
    <div class="flex justify-between mt-6">
      <button onclick="goToSection('A')" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors"><i class="fas fa-arrow-left mr-2"></i>Previous</button>
      <button onclick="nextSection('B','C')" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Next: Production Details <i class="fas fa-arrow-right ml-2"></i></button>
    </div>
  </div>

  <!-- SECTION C: Production Details -->
  <div id="sectionC" class="section-panel bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-yellow-100 rounded-xl flex items-center justify-center"><span class="font-bold text-yellow-700">C</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section C: Production Details</h2><p class="text-gray-500 text-sm">What you grow and how much</p></div>
    </div>
    <div class="space-y-5">
      <div>
        <label class="field-label">Primary Crops / Produce Categories (select all that apply)</label>
        <div class="grid grid-cols-2 md:grid-cols-5 gap-3 mt-2">
          ${['Vegetables','Fruits','Livestock','Poultry','Grains','Dairy','Herbs/Spices','Other'].map(cat => 
            `<label class="checkbox-item bg-gray-50 border border-gray-200 rounded-lg p-3 hover:bg-green-50 hover:border-green-300 transition-colors">
              <input type="checkbox" name="sC_category" value="${cat}" class="accent-green-600">
              <span class="text-sm font-medium text-gray-700">${cat}</span>
            </label>`
          ).join('')}
        </div>
      </div>
      <div>
        <label class="field-label">List Main Crops / Produce Grown *</label>
        <textarea id="sC_mainCrops" class="field-input" rows="3" placeholder="e.g. Tomatoes, Spinach, Cabbage, Avocados, Potatoes..."></textarea>
      </div>
      <div class="grid md:grid-cols-2 gap-5">
        <div>
          <label class="field-label">Current Production Volume (per month/season)</label>
          <input type="text" id="sC_productionVolume" class="field-input" placeholder="e.g. 500 kg/month, 2 tons/season">
        </div>
        <div>
          <label class="field-label">Peak Harvesting Season(s)</label>
          <input type="text" id="sC_harvestSeason" class="field-input" placeholder="e.g. October - March">
        </div>
      </div>
      <div>
        <label class="field-label">Current Market Outlets (select all that apply)</label>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mt-2">
          ${['Local Market/Hawkers','Street Vendors','No Formal Market','Retailers','Wholesalers','Direct to Consumer','Food Processing','Other'].map(outlet => 
            `<label class="checkbox-item bg-gray-50 border border-gray-200 rounded-lg p-3 hover:bg-green-50 hover:border-green-300 transition-colors">
              <input type="checkbox" name="sC_outlet" value="${outlet}" class="accent-green-600">
              <span class="text-sm font-medium text-gray-700">${outlet}</span>
            </label>`
          ).join('')}
        </div>
      </div>
    </div>
    <div class="flex justify-between mt-6">
      <button onclick="goToSection('B')" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors"><i class="fas fa-arrow-left mr-2"></i>Previous</button>
      <button onclick="nextSection('C','D')" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Next: Accreditation <i class="fas fa-arrow-right ml-2"></i></button>
    </div>
  </div>

  <!-- SECTION D: Accreditation & Compliance -->
  <div id="sectionD" class="section-panel bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center"><span class="font-bold text-purple-700">D</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section D: Accreditation & Compliance</h2><p class="text-gray-500 text-sm">Your current certifications and training</p></div>
    </div>
    <div class="space-y-5">
      <div>
        <label class="field-label">Current Certifications Held (select all that apply)</label>
        <div class="grid grid-cols-2 md:grid-cols-3 gap-3 mt-2">
          ${['GAP (Good Agricultural Practices)','HACCP','Food Safety Certificate','Health & Safety','GlobalG.A.P','Organic Certification','None'].map(cert => 
            `<label class="checkbox-item bg-gray-50 border border-gray-200 rounded-lg p-3 hover:bg-purple-50 hover:border-purple-300 transition-colors">
              <input type="checkbox" name="sD_cert" value="${cert}" class="accent-purple-600">
              <span class="text-sm font-medium text-gray-700">${cert}</span>
            </label>`
          ).join('')}
        </div>
      </div>
      <div>
        <label class="field-label">Previous Training Received (select all that apply)</label>
        <div class="grid grid-cols-2 md:grid-cols-4 gap-3 mt-2">
          ${['Agricultural Training','Food Safety Training','Business Management','Financial Literacy','Health & Safety','Export Training','None'].map(tr => 
            `<label class="checkbox-item bg-gray-50 border border-gray-200 rounded-lg p-3 hover:bg-blue-50 hover:border-blue-300 transition-colors">
              <input type="checkbox" name="sD_training" value="${tr}" class="accent-blue-600">
              <span class="text-sm font-medium text-gray-700">${tr}</span>
            </label>`
          ).join('')}
        </div>
      </div>
      <div>
        <label class="field-label">Reason for Applying for Accreditation Support *</label>
        <textarea id="sD_reason" class="field-input" rows="4" placeholder="Please explain why you are applying and what you hope to achieve through this program..."></textarea>
      </div>
    </div>
    <div class="flex justify-between mt-6">
      <button onclick="goToSection('C')" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors"><i class="fas fa-arrow-left mr-2"></i>Previous</button>
      <button onclick="nextSection('D','E')" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Next: Business Info <i class="fas fa-arrow-right ml-2"></i></button>
    </div>
  </div>

  <!-- SECTION E: Business Information -->
  <div id="sectionE" class="section-panel bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-orange-100 rounded-xl flex items-center justify-center"><span class="font-bold text-orange-700">E</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section E: Business Information</h2><p class="text-gray-500 text-sm">Registration and financial details</p></div>
    </div>
    <div class="space-y-5">
      <div>
        <label class="field-label">Do you have a Registered Business?</label>
        <div class="flex gap-4 mt-2">
          <label class="checkbox-item bg-gray-50 border border-gray-200 rounded-lg p-4 flex-1 hover:bg-green-50 hover:border-green-300 transition-colors">
            <input type="radio" name="sE_registered" value="Yes" class="accent-green-600">
            <span class="font-medium text-gray-700">Yes — Registered Business</span>
          </label>
          <label class="checkbox-item bg-gray-50 border border-gray-200 rounded-lg p-4 flex-1 hover:bg-green-50 hover:border-green-300 transition-colors">
            <input type="radio" name="sE_registered" value="No" class="accent-green-600">
            <span class="font-medium text-gray-700">No — Individual / Sole Trader</span>
          </label>
        </div>
      </div>
      <div class="grid md:grid-cols-2 gap-5" id="businessFields">
        <div>
          <label class="field-label">Business / Trading Name</label>
          <input type="text" id="sE_businessName" class="field-input" placeholder="e.g. Nkosi Agri (Pty) Ltd">
        </div>
        <div>
          <label class="field-label">Registration Number</label>
          <input type="text" id="sE_regNo" class="field-input" placeholder="CIPC Registration No.">
        </div>
        <div>
          <label class="field-label">Tax Number (SARS)</label>
          <input type="text" id="sE_taxNo" class="field-input" placeholder="Income Tax Reference Number">
        </div>
        <div>
          <label class="field-label">Number of Employees</label>
          <select id="sE_employees" class="field-input">
            <option value="">Select range</option>
            <option>Just me (sole proprietor)</option><option>1-3 employees</option><option>4-10 employees</option>
            <option>11-25 employees</option><option>More than 25</option>
          </select>
        </div>
      </div>
      <div class="bg-gray-50 border border-gray-200 rounded-xl p-5">
        <h4 class="font-semibold text-gray-800 mb-4"><i class="fas fa-university text-green-600 mr-2"></i>Bank Account Details</h4>
        <div class="grid md:grid-cols-2 gap-4">
          <div>
            <label class="field-label">Bank Name</label>
            <select id="sE_bankName" class="field-input">
              <option value="">Select bank</option>
              <option>ABSA</option><option>FNB</option><option>Standard Bank</option><option>Nedbank</option>
              <option>Capitec</option><option>African Bank</option><option>Postbank</option><option>Other</option>
            </select>
          </div>
          <div>
            <label class="field-label">Account Number</label>
            <input type="text" id="sE_accountNo" class="field-input" placeholder="Your account number">
          </div>
          <div>
            <label class="field-label">Branch Code</label>
            <input type="text" id="sE_branchCode" class="field-input" placeholder="6-digit branch code">
          </div>
          <div>
            <label class="field-label">Account Type</label>
            <select id="sE_accountType" class="field-input">
              <option value="">Select type</option>
              <option>Cheque/Current Account</option><option>Savings Account</option><option>Business Account</option>
            </select>
          </div>
        </div>
      </div>
    </div>
    <div class="flex justify-between mt-6">
      <button onclick="goToSection('D')" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors"><i class="fas fa-arrow-left mr-2"></i>Previous</button>
      <button onclick="nextSection('E','F')" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Next: Support Requirements <i class="fas fa-arrow-right ml-2"></i></button>
    </div>
  </div>

  <!-- SECTION F: Support Requirements -->
  <div id="sectionF" class="section-panel bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-teal-100 rounded-xl flex items-center justify-center"><span class="font-bold text-teal-700">F</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section F: Support Requirements</h2><p class="text-gray-500 text-sm">What type of assistance do you need?</p></div>
    </div>
    <div class="space-y-4">
      <label class="field-label">Select all the support you require from KhanyaKhwezi:</label>
      <div class="grid md:grid-cols-2 gap-3">
        ${[
          ['fas fa-leaf','GAP Accreditation Support','Good Agricultural Practices certification'],
          ['fas fa-star','Quality Grading Training','Learn grading standards for retail'],
          ['fas fa-shield-alt','HACCP Certification','Food safety management system'],
          ['fas fa-handshake','Market Linkage','Connect with retail buyers & exporters'],
          ['fas fa-utensils','Food Safety Training','Food handling & hygiene'],
          ['fas fa-plane','Export Readiness','International market preparation'],
          ['fas fa-hard-hat','Health & Safety Compliance','Farm safety standards'],
          ['fas fa-chart-bar','Business Development','Business skills & financial management'],
          ['fas fa-tint','Irrigation Support','Water management & efficiency'],
          ['fas fa-seedling','Agricultural Training','Crop management best practices']
        ].map(([icon, label, desc]) => 
          `<label class="checkbox-item bg-gray-50 border border-gray-200 rounded-xl p-4 hover:bg-teal-50 hover:border-teal-300 transition-colors">
            <input type="checkbox" name="sF_support" value="${label}" class="accent-teal-600 flex-shrink-0">
            <div>
              <div class="flex items-center gap-2"><i class="${icon} text-teal-600 text-sm"></i><span class="font-semibold text-gray-800 text-sm">${label}</span></div>
              <span class="text-xs text-gray-500">${desc}</span>
            </div>
          </label>`
        ).join('')}
      </div>
      <div>
        <label class="field-label">Other support needed (please specify)</label>
        <textarea id="sF_other" class="field-input" rows="2" placeholder="Any other support requirements not listed above..."></textarea>
      </div>
    </div>
    <div class="flex justify-between mt-6">
      <button onclick="goToSection('E')" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors"><i class="fas fa-arrow-left mr-2"></i>Previous</button>
      <button onclick="nextSection('F','G')" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Next: References <i class="fas fa-arrow-right ml-2"></i></button>
    </div>
  </div>

  <!-- SECTION G: References -->
  <div id="sectionG" class="section-panel bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-indigo-100 rounded-xl flex items-center justify-center"><span class="font-bold text-indigo-700">G</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section G: References</h2><p class="text-gray-500 text-sm">Provide two references who can speak to your farming capability</p></div>
    </div>
    <div class="grid md:grid-cols-2 gap-8">
      <div class="bg-gray-50 rounded-xl p-5 border border-gray-200">
        <h4 class="font-bold text-gray-800 mb-4">Reference 1</h4>
        <div class="space-y-3">
          <div><label class="field-label">Full Name</label><input type="text" id="sG_ref1Name" class="field-input" placeholder="Reference full name"></div>
          <div><label class="field-label">Contact Number</label><input type="tel" id="sG_ref1Contact" class="field-input" placeholder="+27 XX XXX XXXX"></div>
          <div><label class="field-label">Relationship</label>
            <select id="sG_ref1Relation" class="field-input">
              <option value="">Select relationship</option>
              <option>Agricultural Extension Officer</option><option>Community Leader</option><option>Business Partner</option>
              <option>Previous Employer</option><option>Neighbour/Farmer</option><option>Other</option>
            </select>
          </div>
        </div>
      </div>
      <div class="bg-gray-50 rounded-xl p-5 border border-gray-200">
        <h4 class="font-bold text-gray-800 mb-4">Reference 2</h4>
        <div class="space-y-3">
          <div><label class="field-label">Full Name</label><input type="text" id="sG_ref2Name" class="field-input" placeholder="Reference full name"></div>
          <div><label class="field-label">Contact Number</label><input type="tel" id="sG_ref2Contact" class="field-input" placeholder="+27 XX XXX XXXX"></div>
          <div><label class="field-label">Relationship</label>
            <select id="sG_ref2Relation" class="field-input">
              <option value="">Select relationship</option>
              <option>Agricultural Extension Officer</option><option>Community Leader</option><option>Business Partner</option>
              <option>Previous Employer</option><option>Neighbour/Farmer</option><option>Other</option>
            </select>
          </div>
        </div>
      </div>
    </div>
    <div class="flex justify-between mt-6">
      <button onclick="goToSection('F')" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors"><i class="fas fa-arrow-left mr-2"></i>Previous</button>
      <button onclick="nextSection('G','H')" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Next: Declaration <i class="fas fa-arrow-right ml-2"></i></button>
    </div>
  </div>

  <!-- SECTION H: Declaration -->
  <div id="sectionH" class="section-panel bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
    <div class="flex items-center gap-3 mb-6">
      <div class="w-10 h-10 bg-red-100 rounded-xl flex items-center justify-center"><span class="font-bold text-red-700">H</span></div>
      <div><h2 class="text-xl font-bold text-gray-900">Section H: Declaration & Submission</h2><p class="text-gray-500 text-sm">Please review and declare before submitting</p></div>
    </div>
    
    <!-- Document Checklist -->
    <div class="bg-yellow-50 border border-yellow-200 rounded-xl p-5 mb-6">
      <h4 class="font-bold text-yellow-900 mb-3"><i class="fas fa-paperclip mr-2"></i>Document Checklist</h4>
      <p class="text-yellow-800 text-sm mb-3">Please confirm which documents you have ready to submit. Email them to <strong>info@khanyakhwezi.co.za</strong> with your Farmer ID.</p>
      <div class="grid md:grid-cols-2 gap-2">
        ${[
          'Copy of ID Document','Proof of Residence (≤3 months)','Proof of Land Ownership / Title Deed',
          'Lease Agreement (if applicable)','Tribal Authority Letter (if communal)','Bank Confirmation Letter / Statement',
          'Company Registration Certificate','Tax Clearance Certificate','B-BBEE Certificate',
          'GAP Certificate (if held)','HACCP Certificate (if held)','Training Certificates (if any)'
        ].map(doc => 
          `<label class="checkbox-item bg-white border border-yellow-200 rounded-lg p-2 text-sm hover:bg-yellow-100 transition-colors">
            <input type="checkbox" name="sH_docs" value="${doc}" class="accent-yellow-600">
            <span class="text-gray-700">${doc}</span>
          </label>`
        ).join('')}
      </div>
    </div>

    <div class="bg-gray-50 border border-gray-200 rounded-xl p-5 mb-6">
      <h4 class="font-bold text-gray-900 mb-3">Declaration</h4>
      <p class="text-gray-600 text-sm leading-relaxed mb-4">I, the undersigned, hereby declare that all information provided in this application is true, correct, and complete to the best of my knowledge. I understand that providing false information may result in the rejection of my application or termination from the KhanyaKhwezi Accreditation Support Program. I consent to KhanyaKhwezi Harvesting verifying the information provided and contacting my references.</p>
      <div class="space-y-3">
        <label class="checkbox-item">
          <input type="checkbox" id="sH_agree1" class="accent-green-600">
          <span class="text-sm font-medium text-gray-700">I confirm that all information provided is accurate and truthful.</span>
        </label>
        <label class="checkbox-item">
          <input type="checkbox" id="sH_agree2" class="accent-green-600">
          <span class="text-sm font-medium text-gray-700">I consent to KhanyaKhwezi processing my personal and farm information.</span>
        </label>
        <label class="checkbox-item">
          <input type="checkbox" id="sH_agree3" class="accent-green-600">
          <span class="text-sm font-medium text-gray-700">I understand the program requirements and commit to compliance.</span>
        </label>
      </div>
    </div>

    <div class="grid md:grid-cols-2 gap-5">
      <div>
        <label class="field-label">Electronic Signature (Type your full name)</label>
        <input type="text" id="sH_signature" class="field-input font-serif text-lg" placeholder="Type your full name as signature">
      </div>
      <div>
        <label class="field-label">Date</label>
        <input type="date" id="sH_date" class="field-input" value="${new Date().toISOString().split('T')[0]}">
      </div>
    </div>

    <div class="flex justify-between mt-8">
      <button onclick="goToSection('G')" class="bg-gray-100 text-gray-700 px-6 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors"><i class="fas fa-arrow-left mr-2"></i>Previous</button>
      <button onclick="submitApplication()" class="bg-green-700 text-white px-10 py-4 rounded-xl font-bold text-lg hover:bg-green-800 transition-colors shadow-lg">
        <i class="fas fa-paper-plane mr-2"></i>Submit Application
      </button>
    </div>
  </div>

  <!-- Success Panel -->
  <div id="successPanel" class="hidden bg-white rounded-2xl shadow-xl border border-gray-100 p-12 text-center">
    <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
      <i class="fas fa-check-circle text-4xl text-green-600"></i>
    </div>
    <h2 class="text-3xl font-bold text-gray-900 mb-3">Application Submitted!</h2>
    <p class="text-gray-600 text-lg mb-2">Thank you for applying to the KhanyaKhwezi Accreditation Support Program.</p>
    <p class="text-gray-500 mb-6">Reference: <span id="successRefNo" class="font-mono font-bold text-green-700 bg-green-50 px-2 py-1 rounded"></span></p>
    <div class="bg-gray-50 rounded-xl p-5 mb-8 text-left max-w-lg mx-auto">
      <h4 class="font-bold text-gray-800 mb-3">Next Steps:</h4>
      <ol class="space-y-2 text-sm text-gray-600">
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">1</span>Email your documents to info@khanyakhwezi.co.za with your Farmer ID</li>
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">2</span>Our team will review your application within 5 business days</li>
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">3</span>A field assessor may visit your farm for verification</li>
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">4</span>You'll receive approval notification and program schedule</li>
      </ol>
    </div>
    <div class="flex flex-col sm:flex-row gap-4 justify-center">
      <a href="/farmer-portal" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Go to Farmer Portal</a>
      <a href="/" class="bg-gray-100 text-gray-700 px-8 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors">Return to Home</a>
    </div>
  </div>

</div>

<script>
let authToken = null;
let farmerID = null;
let currentSection = 'A';
const sections = ['A','B','C','D','E','F','G','H'];
const completedSections = new Set();

// Check for pending login from portal
const pendingLogin = localStorage.getItem('kkhPendingLogin');
if (pendingLogin) {
  try {
    const creds = JSON.parse(pendingLogin);
    document.getElementById('gateID').value = creds.farmerID;
    document.getElementById('gatePass').value = creds.password;
    localStorage.removeItem('kkhPendingLogin');
  } catch(e) {}
}

// Check for existing auth
const existingToken = localStorage.getItem('kkhToken');
const existingID = localStorage.getItem('kkhFarmerID');
if (existingToken && existingID) {
  authToken = existingToken;
  farmerID = existingID;
  loadApplicationData();
  showApplicationForm();
}

async function gateLogin() {
  const id = document.getElementById('gateID').value.trim();
  const pass = document.getElementById('gatePass').value;
  const err = document.getElementById('gateError');
  
  if (!id || !pass) { err.textContent = 'Please enter your Farmer ID and password.'; err.classList.remove('hidden'); return; }
  
  try {
    const res = await fetch('/api/login', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({farmerID: id, password: pass}) });
    const data = await res.json();
    if (data.success) {
      authToken = data.sessionToken;
      farmerID = data.farmerID;
      localStorage.setItem('kkhToken', authToken);
      localStorage.setItem('kkhFarmerID', farmerID);
      if (data.applicationData) loadSavedData(data.applicationData, data.completedSections || []);
      showApplicationForm();
    } else { err.textContent = data.message; err.classList.remove('hidden'); }
  } catch(e) { err.textContent = 'Login failed. Please try again.'; err.classList.remove('hidden'); }
}

function continueAsGuest() {
  farmerID = 'GUEST-' + Date.now();
  showApplicationForm();
}

function showApplicationForm() {
  document.getElementById('authGate').classList.add('hidden');
  document.getElementById('applicationForm').classList.remove('hidden');
  document.getElementById('appFarmerID').textContent = farmerID || 'Guest';
  document.getElementById('navFarmerID').textContent = farmerID || '';
  document.getElementById('navFarmerID').classList.remove('hidden');
  updateProgress();
}

async function loadApplicationData() {
  if (!authToken) return;
  try {
    const res = await fetch('/api/farmer/profile', { headers: {'Authorization': 'Bearer ' + authToken} });
    const data = await res.json();
    if (data.success && data.farmer.applicationData) {
      loadSavedData(data.farmer.applicationData, data.farmer.completedSections || []);
    }
  } catch(e) {}
}

function loadSavedData(appData, savedSections) {
  savedSections.forEach(s => completedSections.add(s));
  
  if (appData.sectionA) {
    const a = appData.sectionA;
    setVal('sA_fullName', a.fullName); setVal('sA_idNumber', a.idNumber); setVal('sA_dob', a.dob);
    setVal('sA_gender', a.gender); setVal('sA_primaryContact', a.primaryContact);
    setVal('sA_altContact', a.altContact); setVal('sA_email', a.email); setVal('sA_address', a.address);
  }
  if (appData.sectionB) {
    const b = appData.sectionB;
    setVal('sB_farmName', b.farmName); setVal('sB_farmLocation', b.farmLocation); setVal('sB_gps', b.gps);
    setVal('sB_yearsExp', b.yearsExp); setVal('sB_landOwnership', b.landOwnership); setVal('sB_waterSource', b.waterSource);
    setVal('sB_irrigation', b.irrigation); setVal('sB_irrigationType', b.irrigationType);
    setVal('sB_farmSize', b.farmSize); setVal('sB_province', b.province);
  }
  if (appData.sectionC) {
    const c = appData.sectionC;
    setVal('sC_mainCrops', c.mainCrops); setVal('sC_productionVolume', c.productionVolume); setVal('sC_harvestSeason', c.harvestSeason);
    if (c.produceCategories) setCheckboxes('sC_category', c.produceCategories);
    if (c.marketOutlets) setCheckboxes('sC_outlet', c.marketOutlets);
  }
  if (appData.sectionD) {
    const d = appData.sectionD;
    setVal('sD_reason', d.reason);
    if (d.certifications) setCheckboxes('sD_cert', d.certifications);
    if (d.trainingReceived) setCheckboxes('sD_training', d.trainingReceived);
  }
  if (appData.sectionE) {
    const e = appData.sectionE;
    setVal('sE_businessName', e.businessName); setVal('sE_regNo', e.regNo); setVal('sE_taxNo', e.taxNo);
    setVal('sE_employees', e.employees); setVal('sE_bankName', e.bankName); setVal('sE_accountNo', e.accountNo);
    setVal('sE_branchCode', e.branchCode); setVal('sE_accountType', e.accountType);
    if (e.registeredBusiness) document.querySelectorAll('[name="sE_registered"]').forEach(r => { if (r.value === e.registeredBusiness) r.checked = true; });
  }
  if (appData.sectionF) {
    const f = appData.sectionF;
    setVal('sF_other', f.other);
    if (f.supportRequired) setCheckboxes('sF_support', f.supportRequired);
  }
  if (appData.sectionG) {
    const g = appData.sectionG;
    setVal('sG_ref1Name', g.ref1Name); setVal('sG_ref1Contact', g.ref1Contact); setVal('sG_ref1Relation', g.ref1Relation);
    setVal('sG_ref2Name', g.ref2Name); setVal('sG_ref2Contact', g.ref2Contact); setVal('sG_ref2Relation', g.ref2Relation);
  }
  updateProgress();
}

function setVal(id, val) { const el = document.getElementById(id); if (el && val !== undefined) el.value = val; }
function setCheckboxes(name, values) {
  document.querySelectorAll(\`[name="\${name}"]\`).forEach(cb => { cb.checked = values.includes(cb.value); });
}

function goToSection(section) {
  document.querySelectorAll('.section-panel').forEach(p => p.classList.remove('active'));
  document.querySelectorAll('.section-tab').forEach(t => t.classList.remove('active'));
  document.getElementById('section' + section).classList.add('active');
  document.getElementById('tab' + section).classList.add('active');
  currentSection = section;
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

function nextSection(current, next) {
  completedSections.add(current);
  updateProgress();
  saveProgress();
  goToSection(next);
}

function updateProgress() {
  const total = 8;
  const pct = Math.round((completedSections.size / total) * 100);
  document.getElementById('progressDisplay').textContent = pct + '%';
  document.getElementById('formProgressBar').style.width = pct + '%';
  sections.forEach(s => {
    const tab = document.getElementById('tab' + s);
    if (tab && completedSections.has(s)) {
      if (!tab.textContent.startsWith('✓')) tab.textContent = '✓ ' + tab.textContent;
    }
  });
}

function collectFormData() {
  return {
    sectionA: {
      fullName: getVal('sA_fullName'), idNumber: getVal('sA_idNumber'), dob: getVal('sA_dob'),
      gender: getVal('sA_gender'), primaryContact: getVal('sA_primaryContact'),
      altContact: getVal('sA_altContact'), email: getVal('sA_email'), address: getVal('sA_address')
    },
    sectionB: {
      farmName: getVal('sB_farmName'), farmLocation: getVal('sB_farmLocation'), gps: getVal('sB_gps'),
      yearsExp: getVal('sB_yearsExp'), landOwnership: getVal('sB_landOwnership'),
      waterSource: getVal('sB_waterSource'), irrigation: getVal('sB_irrigation'),
      irrigationType: getVal('sB_irrigationType'), farmSize: getVal('sB_farmSize'), province: getVal('sB_province')
    },
    sectionC: {
      produceCategories: getChecked('sC_category'), mainCrops: getVal('sC_mainCrops'),
      productionVolume: getVal('sC_productionVolume'), harvestSeason: getVal('sC_harvestSeason'),
      marketOutlets: getChecked('sC_outlet')
    },
    sectionD: {
      certifications: getChecked('sD_cert'), trainingReceived: getChecked('sD_training'),
      reason: getVal('sD_reason')
    },
    sectionE: {
      registeredBusiness: getRadio('sE_registered'), businessName: getVal('sE_businessName'),
      regNo: getVal('sE_regNo'), taxNo: getVal('sE_taxNo'), employees: getVal('sE_employees'),
      bankName: getVal('sE_bankName'), accountNo: getVal('sE_accountNo'),
      branchCode: getVal('sE_branchCode'), accountType: getVal('sE_accountType')
    },
    sectionF: {
      supportRequired: getChecked('sF_support'), other: getVal('sF_other')
    },
    sectionG: {
      ref1Name: getVal('sG_ref1Name'), ref1Contact: getVal('sG_ref1Contact'), ref1Relation: getVal('sG_ref1Relation'),
      ref2Name: getVal('sG_ref2Name'), ref2Contact: getVal('sG_ref2Contact'), ref2Relation: getVal('sG_ref2Relation')
    },
    sectionH: {
      documentsReady: getChecked('sH_docs'), signature: getVal('sH_signature'), date: getVal('sH_date')
    }
  };
}

function getVal(id) { const el = document.getElementById(id); return el ? el.value : ''; }
function getChecked(name) { return [...document.querySelectorAll(\`[name="\${name}"]:checked\`)].map(c => c.value); }
function getRadio(name) { const r = document.querySelector(\`[name="\${name}"]:checked\`); return r ? r.value : ''; }

async function saveProgress() {
  if (!authToken || farmerID?.startsWith('GUEST')) return;
  const data = collectFormData();
  const pct = Math.round((completedSections.size / 8) * 100);
  try {
    await fetch('/api/application/save', {
      method: 'POST',
      headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + authToken},
      body: JSON.stringify({ data, progress: pct, section: currentSection })
    });
    showToast();
  } catch(e) {}
}

function showToast() {
  const toast = document.getElementById('saveToast');
  toast.classList.add('show');
  setTimeout(() => toast.classList.remove('show'), 2500);
}

async function submitApplication() {
  if (!document.getElementById('sH_agree1').checked || !document.getElementById('sH_agree2').checked || !document.getElementById('sH_agree3').checked) {
    alert('Please confirm all declaration checkboxes before submitting.'); return;
  }
  if (!getVal('sH_signature')) { alert('Please provide your electronic signature (type your full name).'); return; }
  
  completedSections.add('H');
  const data = collectFormData();
  
  if (authToken && !farmerID?.startsWith('GUEST')) {
    try {
      const res = await fetch('/api/application/submit', {
        method: 'POST',
        headers: {'Content-Type': 'application/json', 'Authorization': 'Bearer ' + authToken},
        body: JSON.stringify(data)
      });
      const result = await res.json();
      if (result.success) { showSuccess(); } else { alert('Submission failed: ' + result.message); }
    } catch(e) { showSuccess(); } // Show success even if API fails for demo
  } else {
    showSuccess();
  }
}

function showSuccess() {
  document.getElementById('applicationForm').innerHTML = '';
  document.getElementById('successPanel')?.remove();
  const success = document.createElement('div');
  success.id = 'successPanel';
  success.className = 'bg-white rounded-2xl shadow-xl border border-gray-100 p-12 text-center';
  success.innerHTML = \`
    <div class="w-20 h-20 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6">
      <i class="fas fa-check-circle text-4xl text-green-600"></i>
    </div>
    <h2 class="text-3xl font-bold text-gray-900 mb-3">Application Submitted!</h2>
    <p class="text-gray-600 text-lg mb-2">Thank you for applying to the KhanyaKhwezi Accreditation Support Program.</p>
    <p class="text-gray-500 mb-6">Reference: <span class="font-mono font-bold text-green-700 bg-green-50 px-2 py-1 rounded">\${farmerID || 'KKH-REF-' + Date.now()}</span></p>
    <div class="bg-gray-50 rounded-xl p-5 mb-8 text-left max-w-lg mx-auto">
      <h4 class="font-bold text-gray-800 mb-3">Next Steps:</h4>
      <ol class="space-y-2 text-sm text-gray-600">
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">1</span>Email your documents to info@khanyakhwezi.co.za with your Farmer ID</li>
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">2</span>Our team will review your application within 5 business days</li>
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">3</span>A field assessor may visit your farm for verification</li>
        <li class="flex items-start gap-2"><span class="w-6 h-6 bg-green-600 text-white rounded-full flex-shrink-0 flex items-center justify-center text-xs font-bold">4</span>You will receive approval notification and program schedule</li>
      </ol>
    </div>
    <div class="flex flex-col sm:flex-row gap-4 justify-center">
      <a href="/farmer-portal" class="bg-green-700 text-white px-8 py-3 rounded-xl font-semibold hover:bg-green-800 transition-colors">Go to Farmer Portal</a>
      <a href="/" class="bg-gray-100 text-gray-700 px-8 py-3 rounded-xl font-semibold hover:bg-gray-200 transition-colors">Return to Home</a>
    </div>
  \`;
  document.querySelector('.max-w-5xl').appendChild(success);
}

// Auto-save every 60 seconds
setInterval(saveProgress, 60000);
</script>
</body>
</html>`
}

function adminDashboardHTML() {
  return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard — KhanyaKhwezi Harvesting</title>
<link rel="icon" href="/kkh-logo.png">
<script src="https://cdn.tailwindcss.com"></script>
<link href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@6.4.0/css/all.min.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
  body { font-family: 'Inter', sans-serif; }
  .sidebar { background: linear-gradient(180deg, #0f2027 0%, #203a43 100%); min-height: 100vh; }
  .nav-item { transition: all 0.2s; border-radius: 0.5rem; }
  .nav-item:hover, .nav-item.active { background: rgba(255,255,255,0.1); }
  .status-badge { padding: 2px 10px; border-radius: 9999px; font-size: 0.75rem; font-weight: 600; }
  .status-pending { background: #fef3c7; color: #92400e; }
  .status-submitted { background: #dbeafe; color: #1e40af; }
  .status-approved { background: #dcfce7; color: #166534; }
  .status-rejected { background: #fee2e2; color: #991b1b; }
  .stat-card { transition: all 0.3s; }
  .stat-card:hover { transform: translateY(-2px); box-shadow: 0 8px 25px rgba(0,0,0,0.1); }
  .table-row:hover { background: #f8fafc; }
  .gold-text { color: #c9a84c; }
  .green-bg { background: linear-gradient(135deg, #1a4731 0%, #2d6a4f 100%); }
</style>
</head>
<body class="bg-gray-100">

<!-- Login Screen -->
<div id="adminLogin" class="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-900 to-gray-800">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-md p-10">
    <div class="text-center mb-8">
      <div class="flex justify-center mb-3">
        ${kkhLogoHTML(80)}
      </div>
      <h2 class="text-2xl font-bold text-gray-900">KhanyaKhwezi</h2>
      <p class="text-gray-500 text-sm">Admin Dashboard</p>
    </div>
    <div class="space-y-4">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Admin Email</label>
        <input type="email" id="adminEmail" placeholder="admin@khanyakhwezi.co.za" value="admin@khanyakhwezi.co.za" class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-green-500">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">Password</label>
        <input type="password" id="adminPass" placeholder="Enter admin password" value="KKH@Admin2024" class="w-full border border-gray-300 rounded-lg px-4 py-3 focus:outline-none focus:ring-2 focus:ring-green-500">
      </div>
      <div id="loginErr" class="hidden bg-red-50 border border-red-200 text-red-700 rounded-lg p-3 text-sm"></div>
      <button onclick="adminLogin()" class="w-full bg-green-700 text-white py-3 rounded-lg font-bold hover:bg-green-800 transition-colors">
        <i class="fas fa-lock mr-2"></i>Access Dashboard
      </button>
      <p class="text-center text-xs text-gray-400 mt-2">Demo: admin@khanyakhwezi.co.za / KKH@Admin2024</p>
    </div>
    <div class="mt-4 text-center"><a href="/" class="text-green-700 text-sm hover:underline">← Back to Website</a></div>
  </div>
</div>

<!-- Dashboard -->
<div id="adminDash" class="hidden flex">
  
  <!-- Sidebar -->
  <div class="sidebar w-64 flex-shrink-0 fixed h-full overflow-y-auto z-40">
    <div class="p-6 border-b border-white/10">
      <div class="flex items-center space-x-3">
        ${kkhLogoHTML(42)}
        <div>
          <span class="font-bold text-white block text-sm leading-tight">KhanyaKhwezi</span>
          <span class="text-xs text-gray-400">Admin Portal</span>
        </div>
      </div>
    </div>
    <nav class="p-4 space-y-1">
      <button onclick="showView('overview')" class="nav-item active w-full text-left px-4 py-3 text-gray-300 flex items-center gap-3 text-sm">
        <i class="fas fa-th-large w-5"></i>Overview
      </button>
      <button onclick="showView('farmers')" class="nav-item w-full text-left px-4 py-3 text-gray-300 flex items-center gap-3 text-sm">
        <i class="fas fa-users w-5"></i>All Farmers
      </button>
      <button onclick="showView('pending')" class="nav-item w-full text-left px-4 py-3 text-gray-300 flex items-center gap-3 text-sm">
        <i class="fas fa-clock w-5"></i>Pending Review
        <span id="pendingBadge" class="ml-auto bg-yellow-500 text-white text-xs px-2 py-0.5 rounded-full"></span>
      </button>
      <button onclick="showView('approved')" class="nav-item w-full text-left px-4 py-3 text-gray-300 flex items-center gap-3 text-sm">
        <i class="fas fa-check-circle w-5"></i>Approved
      </button>
      <button onclick="showView('export')" class="nav-item w-full text-left px-4 py-3 text-gray-300 flex items-center gap-3 text-sm">
        <i class="fas fa-file-excel w-5"></i>Export Data
      </button>
      <div class="border-t border-white/10 my-2"></div>
      <a href="/" class="nav-item w-full text-left px-4 py-3 text-gray-300 flex items-center gap-3 text-sm">
        <i class="fas fa-globe w-5"></i>View Website
      </a>
      <button onclick="adminLogout()" class="nav-item w-full text-left px-4 py-3 text-red-400 flex items-center gap-3 text-sm">
        <i class="fas fa-sign-out-alt w-5"></i>Logout
      </button>
    </nav>
  </div>

  <!-- Main Content -->
  <div class="ml-64 flex-1 min-h-screen">
    
    <!-- Top Bar -->
    <div class="bg-white border-b border-gray-200 px-8 py-4 flex justify-between items-center sticky top-0 z-30">
      <div>
        <h1 id="pageTitle" class="text-xl font-bold text-gray-900">Dashboard Overview</h1>
        <p class="text-gray-500 text-xs mt-0.5">KhanyaKhwezi Harvesting — Farmer Management System</p>
      </div>
      <div class="flex items-center gap-3">
        <button onclick="refreshData()" class="bg-gray-100 text-gray-600 px-3 py-2 rounded-lg text-sm hover:bg-gray-200 transition-colors">
          <i class="fas fa-sync-alt mr-1"></i>Refresh
        </button>
        <button onclick="loadSeedData()" class="bg-green-700 text-white px-3 py-2 rounded-lg text-sm hover:bg-green-800 transition-colors">
          <i class="fas fa-database mr-1"></i>Load Demo Data
        </button>
      </div>
    </div>

    <!-- Content Area -->
    <div class="p-8">
      
      <!-- Overview View -->
      <div id="view-overview">
        <!-- Stats Grid -->
        <div class="grid grid-cols-2 md:grid-cols-4 gap-5 mb-8">
          <div class="stat-card bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <div class="flex items-center justify-between mb-3">
              <div class="w-10 h-10 bg-blue-100 rounded-xl flex items-center justify-center"><i class="fas fa-users text-blue-600"></i></div>
              <span class="text-xs text-blue-600 font-medium">Total</span>
            </div>
            <div class="text-3xl font-bold text-gray-900" id="totalCount">0</div>
            <div class="text-gray-500 text-sm mt-1">Total Farmers</div>
          </div>
          <div class="stat-card bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <div class="flex items-center justify-between mb-3">
              <div class="w-10 h-10 bg-yellow-100 rounded-xl flex items-center justify-center"><i class="fas fa-clock text-yellow-600"></i></div>
              <span class="text-xs text-yellow-600 font-medium">Needs Review</span>
            </div>
            <div class="text-3xl font-bold text-gray-900" id="pendingCount">0</div>
            <div class="text-gray-500 text-sm mt-1">Pending Applications</div>
          </div>
          <div class="stat-card bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <div class="flex items-center justify-between mb-3">
              <div class="w-10 h-10 bg-green-100 rounded-xl flex items-center justify-center"><i class="fas fa-check-circle text-green-600"></i></div>
              <span class="text-xs text-green-600 font-medium">Active</span>
            </div>
            <div class="text-3xl font-bold text-gray-900" id="approvedCount">0</div>
            <div class="text-gray-500 text-sm mt-1">Approved Farmers</div>
          </div>
          <div class="stat-card bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <div class="flex items-center justify-between mb-3">
              <div class="w-10 h-10 bg-purple-100 rounded-xl flex items-center justify-center"><i class="fas fa-paper-plane text-purple-600"></i></div>
              <span class="text-xs text-purple-600 font-medium">Submitted</span>
            </div>
            <div class="text-3xl font-bold text-gray-900" id="submittedCount">0</div>
            <div class="text-gray-500 text-sm mt-1">Awaiting Review</div>
          </div>
        </div>
        
        <!-- Charts -->
        <div class="grid md:grid-cols-2 gap-6 mb-6">
          <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <h3 class="font-bold text-gray-900 mb-4">Application Status Distribution</h3>
            <canvas id="statusChart" height="250"></canvas>
          </div>
          <div class="bg-white rounded-2xl p-6 shadow-sm border border-gray-100">
            <h3 class="font-bold text-gray-900 mb-4">Province Distribution</h3>
            <canvas id="provinceChart" height="250"></canvas>
          </div>
        </div>

        <!-- Recent Activity -->
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100">
          <div class="p-6 border-b border-gray-100 flex justify-between items-center">
            <h3 class="font-bold text-gray-900">Recent Applications</h3>
            <button onclick="showView('farmers')" class="text-green-700 text-sm font-medium hover:underline">View All →</button>
          </div>
          <div id="recentFarmers" class="divide-y divide-gray-50"></div>
        </div>
      </div>

      <!-- Farmers View -->
      <div id="view-farmers" class="hidden">
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100">
          <div class="p-6 border-b border-gray-100 flex flex-col md:flex-row md:items-center justify-between gap-4">
            <h3 class="font-bold text-gray-900">All Registered Farmers</h3>
            <div class="flex gap-3">
              <input type="text" id="searchInput" onkeyup="filterTable()" placeholder="Search farmers..." class="border border-gray-300 rounded-lg px-4 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500 w-64">
              <select id="statusFilter" onchange="filterTable()" class="border border-gray-300 rounded-lg px-3 py-2 text-sm focus:outline-none focus:ring-2 focus:ring-green-500">
                <option value="">All Status</option>
                <option value="pending">Pending</option>
                <option value="submitted">Submitted</option>
                <option value="approved">Approved</option>
                <option value="rejected">Rejected</option>
              </select>
            </div>
          </div>
          <div class="overflow-x-auto">
            <table class="w-full">
              <thead class="bg-gray-50 border-b border-gray-100">
                <tr>
                  <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">Farmer</th>
                  <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">Farmer ID</th>
                  <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">Province</th>
                  <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">Progress</th>
                  <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">Status</th>
                  <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">Date</th>
                  <th class="text-left px-6 py-3 text-xs font-semibold text-gray-500 uppercase tracking-wider">Actions</th>
                </tr>
              </thead>
              <tbody id="farmersTable" class="divide-y divide-gray-50"></tbody>
            </table>
          </div>
        </div>
      </div>

      <!-- Pending View -->
      <div id="view-pending" class="hidden">
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100">
          <div class="p-6 border-b border-gray-100">
            <h3 class="font-bold text-gray-900">Applications Pending Review</h3>
          </div>
          <div id="pendingList" class="divide-y divide-gray-100"></div>
        </div>
      </div>

      <!-- Approved View -->
      <div id="view-approved" class="hidden">
        <div class="bg-white rounded-2xl shadow-sm border border-gray-100">
          <div class="p-6 border-b border-gray-100">
            <h3 class="font-bold text-gray-900">Approved Farmers — Active Partners</h3>
          </div>
          <div id="approvedList" class="divide-y divide-gray-100"></div>
        </div>
      </div>

      <!-- Export View -->
      <div id="view-export" class="hidden">
        <div class="max-w-2xl">
          <div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-8">
            <h3 class="text-xl font-bold text-gray-900 mb-2">Export Farmer Data</h3>
            <p class="text-gray-500 text-sm mb-6">Download all farmer application data for offline analysis and reporting</p>
            
            <div class="space-y-4">
              <div class="bg-green-50 border border-green-200 rounded-xl p-5">
                <div class="flex items-start gap-4">
                  <div class="w-12 h-12 bg-green-600 rounded-xl flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-file-csv text-white text-xl"></i>
                  </div>
                  <div class="flex-1">
                    <h4 class="font-bold text-gray-900">Complete Farmer Database (CSV)</h4>
                    <p class="text-gray-500 text-sm mt-1">All farmer records with personal, farm, production, business info and document status. Opens in Excel, Google Sheets.</p>
                    <button onclick="exportCSV()" class="mt-3 bg-green-700 text-white px-5 py-2 rounded-lg text-sm font-semibold hover:bg-green-800 transition-colors">
                      <i class="fas fa-download mr-2"></i>Download CSV
                    </button>
                  </div>
                </div>
              </div>

              <div class="bg-blue-50 border border-blue-200 rounded-xl p-5">
                <div class="flex items-start gap-4">
                  <div class="w-12 h-12 bg-blue-600 rounded-xl flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-file-alt text-white text-xl"></i>
                  </div>
                  <div class="flex-1">
                    <h4 class="font-bold text-gray-900">Document Tracking Report</h4>
                    <p class="text-gray-500 text-sm mt-1">Shows which farmers have submitted which documents and what's still outstanding.</p>
                    <button onclick="exportDocReport()" class="mt-3 bg-blue-700 text-white px-5 py-2 rounded-lg text-sm font-semibold hover:bg-blue-800 transition-colors">
                      <i class="fas fa-download mr-2"></i>Download Report
                    </button>
                  </div>
                </div>
              </div>

              <div class="bg-purple-50 border border-purple-200 rounded-xl p-5">
                <div class="flex items-start gap-4">
                  <div class="w-12 h-12 bg-purple-600 rounded-xl flex items-center justify-center flex-shrink-0">
                    <i class="fas fa-print text-white text-xl"></i>
                  </div>
                  <div class="flex-1">
                    <h4 class="font-bold text-gray-900">Print Application Summary</h4>
                    <p class="text-gray-500 text-sm mt-1">Generate a printable summary of all submitted applications for office filing.</p>
                    <button onclick="window.print()" class="mt-3 bg-purple-700 text-white px-5 py-2 rounded-lg text-sm font-semibold hover:bg-purple-800 transition-colors">
                      <i class="fas fa-print mr-2"></i>Print Summary
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</div>

<!-- Farmer Detail Modal -->
<div id="farmerModal" class="hidden fixed inset-0 bg-black/50 z-50 flex items-center justify-center p-4">
  <div class="bg-white rounded-2xl shadow-2xl w-full max-w-3xl max-h-screen overflow-y-auto">
    <div class="p-6 border-b border-gray-100 flex justify-between items-center sticky top-0 bg-white z-10">
      <h3 class="text-xl font-bold text-gray-900" id="modalTitle">Farmer Details</h3>
      <button onclick="closeModal()" class="text-gray-400 hover:text-gray-600 text-xl"><i class="fas fa-times"></i></button>
    </div>
    <div id="modalContent" class="p-6"></div>
  </div>
</div>

<script>
let adminToken = null;
let allFarmers = [];

async function adminLogin() {
  const email = document.getElementById('adminEmail').value;
  const pass = document.getElementById('adminPass').value;
  const err = document.getElementById('loginErr');
  
  try {
    const res = await fetch('/api/admin/login', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({username: email, password: pass}) });
    const data = await res.json();
    if (data.success) {
      adminToken = data.token;
      sessionStorage.setItem('adminToken', adminToken);
      document.getElementById('adminLogin').classList.add('hidden');
      document.getElementById('adminDash').classList.remove('hidden');
      loadDashboard();
    } else { err.textContent = data.message; err.classList.remove('hidden'); }
  } catch(e) { err.textContent = 'Login failed.'; err.classList.remove('hidden'); }
}

function adminLogout() {
  sessionStorage.removeItem('adminToken');
  window.location.reload();
}

// Auto-login if session exists
const savedToken = sessionStorage.getItem('adminToken');
if (savedToken) {
  adminToken = savedToken;
  document.getElementById('adminLogin').classList.add('hidden');
  document.getElementById('adminDash').classList.remove('hidden');
  loadDashboard();
}

async function loadDashboard() {
  await fetchFarmers();
  renderOverview();
  renderFarmersTable();
  renderPendingList();
  renderApprovedList();
}

async function fetchFarmers() {
  try {
    const res = await fetch('/api/admin/farmers', { headers: {'Authorization': 'Bearer ' + adminToken} });
    const data = await res.json();
    if (data.success) allFarmers = data.farmers;
    updateBadges();
  } catch(e) { console.error('Failed to load farmers', e); }
}

function updateBadges() {
  const pending = allFarmers.filter(f => f.status === 'submitted' || f.status === 'pending').length;
  document.getElementById('pendingBadge').textContent = pending > 0 ? pending : '';
  document.getElementById('totalCount').textContent = allFarmers.length;
  document.getElementById('pendingCount').textContent = allFarmers.filter(f => f.status === 'pending').length;
  document.getElementById('approvedCount').textContent = allFarmers.filter(f => f.status === 'approved').length;
  document.getElementById('submittedCount').textContent = allFarmers.filter(f => f.status === 'submitted').length;
}

function renderOverview() {
  // Status chart
  const statusCounts = { pending: 0, submitted: 0, approved: 0, rejected: 0 };
  allFarmers.forEach(f => { if (statusCounts[f.status] !== undefined) statusCounts[f.status]++; });
  
  const ctx1 = document.getElementById('statusChart').getContext('2d');
  if (window.statusChartInst) window.statusChartInst.destroy();
  window.statusChartInst = new Chart(ctx1, {
    type: 'doughnut',
    data: {
      labels: ['Pending', 'Submitted', 'Approved', 'Rejected'],
      datasets: [{ data: Object.values(statusCounts), backgroundColor: ['#fcd34d','#93c5fd','#86efac','#fca5a5'], borderWidth: 0 }]
    },
    options: { responsive: true, plugins: { legend: { position: 'bottom' } }, cutout: '65%' }
  });
  
  // Province chart
  const provinces = {};
  allFarmers.forEach(f => {
    const p = f.applicationData?.sectionB?.province || 'Unknown';
    provinces[p] = (provinces[p] || 0) + 1;
  });
  
  const ctx2 = document.getElementById('provinceChart').getContext('2d');
  if (window.provinceChartInst) window.provinceChartInst.destroy();
  window.provinceChartInst = new Chart(ctx2, {
    type: 'bar',
    data: {
      labels: Object.keys(provinces),
      datasets: [{ label: 'Farmers', data: Object.values(provinces), backgroundColor: '#2d6a4f', borderRadius: 6 }]
    },
    options: { responsive: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } } }
  });
  
  // Recent farmers
  const recent = [...allFarmers].sort((a,b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()).slice(0, 5);
  document.getElementById('recentFarmers').innerHTML = recent.length ? recent.map(f => farmerRowHTML(f)).join('') : '<div class="p-8 text-center text-gray-400"><i class="fas fa-inbox text-3xl mb-2 block"></i>No farmers yet. Click "Load Demo Data" to get started.</div>';
}

function renderFarmersTable() {
  const tbody = document.getElementById('farmersTable');
  if (!allFarmers.length) {
    tbody.innerHTML = '<tr><td colspan="7" class="px-6 py-12 text-center text-gray-400"><i class="fas fa-users text-3xl mb-2 block"></i>No farmers registered yet</td></tr>';
    return;
  }
  tbody.innerHTML = allFarmers.map(f => {
    const name = f.applicationData?.sectionA?.fullName || f.fullName || 'N/A';
    const email = f.applicationData?.sectionA?.email || f.email || 'N/A';
    const province = f.applicationData?.sectionB?.province || '—';
    return \`<tr class="table-row">
      <td class="px-6 py-4">
        <div class="flex items-center gap-3">
          <div class="w-9 h-9 rounded-full bg-green-100 flex items-center justify-center font-bold text-green-700">\${name.charAt(0)}</div>
          <div><div class="font-medium text-gray-900 text-sm">\${name}</div><div class="text-gray-400 text-xs">\${email}</div></div>
        </div>
      </td>
      <td class="px-6 py-4"><span class="font-mono text-xs text-gray-600 bg-gray-100 px-2 py-1 rounded">\${f.farmerID}</span></td>
      <td class="px-6 py-4 text-sm text-gray-600">\${province}</td>
      <td class="px-6 py-4">
        <div class="flex items-center gap-2">
          <div class="flex-1 h-2 bg-gray-100 rounded-full overflow-hidden w-16">
            <div class="h-full bg-green-500 rounded-full" style="width:\${f.progress || 0}%"></div>
          </div>
          <span class="text-xs text-gray-500">\${f.progress || 0}%</span>
        </div>
      </td>
      <td class="px-6 py-4"><span class="status-badge status-\${f.status}">\${f.status}</span></td>
      <td class="px-6 py-4 text-xs text-gray-500">\${f.createdAt ? new Date(f.createdAt).toLocaleDateString('en-ZA') : '—'}</td>
      <td class="px-6 py-4">
        <button onclick="viewFarmer('\${f.farmerID}')" class="text-green-700 hover:text-green-900 text-sm font-medium mr-3">View</button>
        <button onclick="quickStatus('\${f.farmerID}')" class="text-blue-600 hover:text-blue-800 text-sm font-medium">Status</button>
      </td>
    </tr>\`;
  }).join('');
}

function renderPendingList() {
  const pending = allFarmers.filter(f => f.status === 'submitted' || f.status === 'pending');
  const el = document.getElementById('pendingList');
  el.innerHTML = pending.length ? pending.map(f => farmerRowHTML(f, true)).join('') :
    '<div class="p-12 text-center text-gray-400"><i class="fas fa-check-circle text-3xl mb-2 block text-green-400"></i>No pending applications!</div>';
}

function renderApprovedList() {
  const approved = allFarmers.filter(f => f.status === 'approved');
  const el = document.getElementById('approvedList');
  el.innerHTML = approved.length ? approved.map(f => farmerRowHTML(f)).join('') :
    '<div class="p-12 text-center text-gray-400"><i class="fas fa-user-check text-3xl mb-2 block"></i>No approved farmers yet</div>';
}

function farmerRowHTML(f, showActions = false) {
  const name = f.applicationData?.sectionA?.fullName || f.fullName || 'Unknown';
  const email = f.applicationData?.sectionA?.email || f.email || '—';
  const province = f.applicationData?.sectionB?.province || '—';
  return \`<div class="p-4 flex items-center justify-between hover:bg-gray-50 transition-colors">
    <div class="flex items-center gap-3">
      <div class="w-10 h-10 rounded-full bg-green-100 flex items-center justify-center font-bold text-green-700">\${name.charAt(0)}</div>
      <div>
        <div class="font-medium text-gray-900 text-sm">\${name}</div>
        <div class="text-gray-400 text-xs">\${f.farmerID} · \${email} · \${province}</div>
      </div>
    </div>
    <div class="flex items-center gap-3">
      <span class="status-badge status-\${f.status}">\${f.status}</span>
      <span class="text-xs text-gray-400">\${f.progress || 0}% complete</span>
      <button onclick="viewFarmer('\${f.farmerID}')" class="text-green-700 hover:text-green-900 text-sm font-medium">View →</button>
    </div>
  </div>\`;
}

function showView(view) {
  ['overview','farmers','pending','approved','export'].forEach(v => {
    const el = document.getElementById('view-' + v);
    if (el) el.classList.add('hidden');
  });
  document.getElementById('view-' + view).classList.remove('hidden');
  document.getElementById('pageTitle').textContent = {
    overview: 'Dashboard Overview', farmers: 'All Farmers', pending: 'Pending Review',
    approved: 'Approved Farmers', export: 'Export Data'
  }[view];
  document.querySelectorAll('.nav-item').forEach(n => n.classList.remove('active'));
}

async function viewFarmer(id) {
  try {
    const res = await fetch('/api/admin/farmers/' + id, { headers: {'Authorization': 'Bearer ' + adminToken} });
    const data = await res.json();
    if (!data.success) return;
    const f = data.farmer;
    const ad = f.applicationData || {};
    const a = ad.sectionA || {};
    const b = ad.sectionB || {};
    const c = ad.sectionC || {};
    const d = ad.sectionD || {};
    const e = ad.sectionE || {};
    const fSec = ad.sectionF || {};
    
    document.getElementById('modalTitle').textContent = (a.fullName || f.fullName) + ' — ' + f.farmerID;
    document.getElementById('modalContent').innerHTML = \`
      <div class="space-y-5">
        <div class="flex justify-between items-center bg-gray-50 rounded-xl p-4">
          <div><span class="text-sm text-gray-500">Status:</span> <span class="status-badge status-\${f.status} ml-2">\${f.status}</span></div>
          <div><span class="text-sm text-gray-500">Progress:</span> <strong class="text-green-700">\${f.progress || 0}%</strong></div>
          <div><span class="text-sm text-gray-500">Applied:</span> <span class="text-sm">\${f.createdAt ? new Date(f.createdAt).toLocaleDateString('en-ZA') : '—'}</span></div>
        </div>
        
        <div class="grid md:grid-cols-2 gap-4">
          <div class="bg-gray-50 rounded-xl p-4">
            <h4 class="font-bold text-gray-800 mb-3 text-sm uppercase tracking-wide">Personal Information</h4>
            <div class="space-y-2 text-sm">
              <div class="flex gap-2"><span class="text-gray-500 w-24">Full Name:</span><span>\${a.fullName || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">ID Number:</span><span>\${a.idNumber || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Gender:</span><span>\${a.gender || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Phone:</span><span>\${a.primaryContact || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Email:</span><span>\${a.email || f.email || '—'}</span></div>
            </div>
          </div>
          <div class="bg-gray-50 rounded-xl p-4">
            <h4 class="font-bold text-gray-800 mb-3 text-sm uppercase tracking-wide">Farm Information</h4>
            <div class="space-y-2 text-sm">
              <div class="flex gap-2"><span class="text-gray-500 w-24">Farm Name:</span><span>\${b.farmName || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Location:</span><span>\${b.farmLocation || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Province:</span><span>\${b.province || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Land Type:</span><span>\${b.landOwnership || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Water:</span><span>\${b.waterSource || '—'}</span></div>
            </div>
          </div>
          <div class="bg-gray-50 rounded-xl p-4">
            <h4 class="font-bold text-gray-800 mb-3 text-sm uppercase tracking-wide">Production</h4>
            <div class="space-y-2 text-sm">
              <div class="flex gap-2"><span class="text-gray-500 w-24">Crops:</span><span>\${(c.mainCrops || '—')}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Volume:</span><span>\${c.productionVolume || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Season:</span><span>\${c.harvestSeason || '—'}</span></div>
            </div>
          </div>
          <div class="bg-gray-50 rounded-xl p-4">
            <h4 class="font-bold text-gray-800 mb-3 text-sm uppercase tracking-wide">Business</h4>
            <div class="space-y-2 text-sm">
              <div class="flex gap-2"><span class="text-gray-500 w-24">Registered:</span><span>\${e.registeredBusiness || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Business:</span><span>\${e.businessName || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Employees:</span><span>\${e.employees || '—'}</span></div>
              <div class="flex gap-2"><span class="text-gray-500 w-24">Bank:</span><span>\${e.bankName || '—'}</span></div>
            </div>
          </div>
        </div>

        <div class="bg-gray-50 rounded-xl p-4">
          <h4 class="font-bold text-gray-800 mb-3 text-sm uppercase tracking-wide">Support Required</h4>
          <div class="flex flex-wrap gap-2">
            \${(fSec.supportRequired || []).map(s => \`<span class="bg-green-100 text-green-800 text-xs px-3 py-1 rounded-full">\${s}</span>\`).join('') || '<span class="text-gray-400 text-sm">None specified</span>'}
          </div>
        </div>

        <div class="bg-gray-50 rounded-xl p-4">
          <h4 class="font-bold text-gray-800 mb-3 text-sm uppercase tracking-wide">Admin Actions</h4>
          <div class="flex gap-3 flex-wrap">
            <button onclick="updateStatus('\${f.farmerID}', 'approved')" class="bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-green-700 transition-colors"><i class="fas fa-check mr-1"></i>Approve</button>
            <button onclick="updateStatus('\${f.farmerID}', 'rejected')" class="bg-red-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-red-700 transition-colors"><i class="fas fa-times mr-1"></i>Reject</button>
            <button onclick="updateStatus('\${f.farmerID}', 'pending')" class="bg-yellow-600 text-white px-4 py-2 rounded-lg text-sm font-semibold hover:bg-yellow-700 transition-colors"><i class="fas fa-undo mr-1"></i>Set Pending</button>
          </div>
          \${f.adminComments ? \`<div class="mt-3 bg-blue-50 border border-blue-200 rounded-lg p-3 text-sm text-blue-800"><strong>Admin Notes:</strong> \${f.adminComments}</div>\` : ''}
        </div>
      </div>
    \`;
    document.getElementById('farmerModal').classList.remove('hidden');
  } catch(e) { alert('Failed to load farmer details'); }
}

async function updateStatus(id, status) {
  const comments = status === 'rejected' ? prompt('Reason for rejection (optional):') : null;
  try {
    const res = await fetch('/api/admin/farmers/' + id + '/status', {
      method: 'PATCH',
      headers: {'Content-Type':'application/json', 'Authorization': 'Bearer ' + adminToken},
      body: JSON.stringify({status, comments: comments || ''})
    });
    const data = await res.json();
    if (data.success) {
      closeModal();
      await loadDashboard();
      alert('Status updated to: ' + status);
    }
  } catch(e) { alert('Failed to update status'); }
}

async function quickStatus(id) {
  const status = prompt('Enter new status (pending/submitted/approved/rejected):');
  if (status) await updateStatus(id, status.toLowerCase());
}

function closeModal() { document.getElementById('farmerModal').classList.add('hidden'); }

async function exportCSV() {
  const res = await fetch('/api/admin/export/csv', { headers: {'Authorization': 'Bearer ' + adminToken} });
  const blob = await res.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = 'KKH_Farmers_' + new Date().toISOString().split('T')[0] + '.csv';
  a.click(); URL.revokeObjectURL(url);
}

function exportDocReport() {
  const rows = [['Farmer ID','Name','ID Doc','Proof of Residence','Land Ownership','Lease Agreement','Bank Statement','Company Reg','Tax Clearance','B-BBEE','GAP Cert','HACCP Cert','Submitted Date'].join(',')];
  allFarmers.forEach(f => {
    const docs = f.documentsUploaded || [];
    const check = (doc) => docs.some(d => d.toLowerCase().includes(doc.toLowerCase())) ? 'YES' : 'NO';
    rows.push([
      f.farmerID,
      '"' + (f.applicationData?.sectionA?.fullName || f.fullName || '') + '"',
      check('ID'), check('Residence'), check('Land'), check('Lease'), check('Bank'), check('Registration'), check('Tax'), check('B-BBEE'), check('GAP'), check('HACCP'),
      f.submittedAt || '—'
    ].join(','));
  });
  const blob = new Blob([rows.join('\\n')], {type:'text/csv'});
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url; a.download = 'KKH_Document_Report.csv';
  a.click(); URL.revokeObjectURL(url);
}

function filterTable() {
  const search = document.getElementById('searchInput').value.toLowerCase();
  const status = document.getElementById('statusFilter').value;
  const filtered = allFarmers.filter(f => {
    const name = (f.applicationData?.sectionA?.fullName || f.fullName || '').toLowerCase();
    const email = (f.applicationData?.sectionA?.email || f.email || '').toLowerCase();
    const matchSearch = !search || name.includes(search) || email.includes(search) || f.farmerID.toLowerCase().includes(search);
    const matchStatus = !status || f.status === status;
    return matchSearch && matchStatus;
  });
  const tbody = document.getElementById('farmersTable');
  if (!filtered.length) { tbody.innerHTML = '<tr><td colspan="7" class="px-6 py-8 text-center text-gray-400">No farmers match your search</td></tr>'; return; }
  const tempFarmers = allFarmers;
  allFarmers = filtered;
  renderFarmersTable();
  allFarmers = tempFarmers;
}

async function loadSeedData() {
  const res = await fetch('/api/admin/seed', { method: 'POST', headers: {'Authorization': 'Bearer ' + adminToken} });
  const data = await res.json();
  if (data.success) { await loadDashboard(); alert(data.message); }
}

async function refreshData() {
  await loadDashboard();
}
</script>
</body>
</html>`
}

function adminFarmerDetailHTML() {
  return `<!DOCTYPE html>
<html><head><title>Farmer Detail</title></head>
<body><script>window.location.href = '/admin';</script></body></html>`
}
