import React, { useState, useEffect, useMemo } from 'react';
import { 
  Droplet, ShoppingBag, Truck, User, Shield, LogOut, CheckCircle, Clock, 
  XCircle, Search, Edit3, Plus, Trash2, Filter, Settings, RefreshCw, AlertCircle, Phone, MapPin, DollarSign, CreditCard
} from 'lucide-react';

// ==========================================
// INITIAL MOCK DATA
// ==========================================

const INITIAL_PRODUCTS = [
  // A. Water Refills
  { id: 'p1', category: 'refill', name: 'Standard Rectangular Gallon with Faucet', capacity: '20 Liters', price: 30, active: true, image: 'rect-faucet', desc: 'Refill for 20L rectangular container with built-in spigot/faucet.' },
  { id: 'p2', category: 'refill', name: 'Standard Round Gallon', capacity: '20 Liters', price: 30, active: true, image: 'round', desc: 'Refill for standard 20L round water dispenser gallon.' },
  { id: 'p3', category: 'refill', name: 'Half-Size Rectangular Gallon with Faucet', capacity: '10 Liters', price: 15, active: true, image: 'rect-faucet-half', desc: 'Refill for 10L compact rectangular container with faucet.' },
  
  // B. Empty Gallons Only
  { id: 'p4', category: 'empty', name: 'Half-Size Rectangular Gallon with Faucet (Empty)', capacity: '10 Liters', price: 90, active: true, image: 'rect-faucet-half', desc: 'Brand new empty 10L rectangular plastic container with faucet.' },
  { id: 'p5', category: 'empty', name: 'Standard Round Gallon (Empty)', capacity: '20 Liters', price: 180, active: true, image: 'round', desc: 'Brand new empty 20L heavy-duty round container.' },
  { id: 'p6', category: 'empty', name: 'Standard Rectangular Gallon with Faucet (Empty)', capacity: '20 Liters', price: 180, active: true, image: 'rect-faucet', desc: 'Brand new empty 20L rectangular container with high-grade faucet.' },
  
  // C. New Gallon with Water
  { id: 'p7', category: 'new_with_water', name: 'Standard Rectangular Gallon with Faucet + Water', capacity: '20 Liters', price: 200, active: true, image: 'rect-faucet', desc: 'Brand new 20L rectangular container complete with purified water.' },
  { id: 'p8', category: 'new_with_water', name: 'Standard Round Gallon + Water', capacity: '20 Liters', price: 200, active: true, image: 'round', desc: 'Brand new 20L round gallon complete with purified water.' },
  { id: 'p9', category: 'new_with_water', name: 'Half-Size Rectangular Gallon + Water', capacity: '10 Liters', price: 100, active: true, image: 'rect-faucet-half', desc: 'Brand new 10L rectangular container complete with purified water.' }
];

const INITIAL_ORDERS = [
  {
    id: 'ORD-1001',
    customerId: 'cust1',
    customerName: 'Juan Dela Cruz',
    contactNumber: '09171234567',
    deliveryAddress: '123 Mabini St., Brgy. San Josef Sur, Cabanatuan City',
    items: [
      { productId: 'p1', name: 'Standard Rectangular Gallon with Faucet', capacity: '20 Liters', unitPrice: 30, quantity: 3 }
    ],
    totalAmount: 90,
    paymentMethod: 'COD',
    paymentStatus: 'Pending',
    orderStatus: 'Pending',
    orderDate: '2026-10-28 09:30 AM',
    requestedSchedule: { date: '2026-10-29', time: '10:00 AM - 12:00 PM' },
    confirmedSchedule: null,
    deliveryInstructions: 'Please leave with guard if absent.',
    cancellationReason: null
  },
  {
    id: 'ORD-1002',
    customerId: 'cust1',
    customerName: 'Juan Dela Cruz',
    contactNumber: '09171234567',
    deliveryAddress: '123 Mabini St., Brgy. San Josef Sur, Cabanatuan City',
    items: [
      { productId: 'p7', name: 'Standard Rectangular Gallon with Faucet + Water', capacity: '20 Liters', unitPrice: 200, quantity: 1 },
      { productId: 'p1', name: 'Standard Rectangular Gallon with Faucet', capacity: '20 Liters', unitPrice: 30, quantity: 2 }
    ],
    totalAmount: 260,
    paymentMethod: 'GCash',
    paymentStatus: 'Verified',
    orderStatus: 'Out for Delivery',
    orderDate: '2026-10-27 02:15 PM',
    requestedSchedule: { date: '2026-10-28', time: '02:00 PM - 04:00 PM' },
    confirmedSchedule: '2026-10-28 02:30 PM',
    deliveryInstructions: 'Blue gate near sari-sari store.',
    cancellationReason: null
  }
];

const INITIAL_PAYMENT_CONFIG = {
  gcash: { title: 'GCash', accountName: 'JP WATER REFILLING', accountNumber: '0949-360-8711', instructions: 'Send payment via GCash Express Send. Save transaction reference number.' },
  maya: { title: 'Maya', accountName: 'JP WATER REFILLING', accountNumber: '0908-298-0925', instructions: 'Transfer via Maya Wallet to mobile number above.' },
  bank: { title: 'Online Banking (BDO)', accountName: 'JP Water Refilling Station', accountNumber: '0012-3456-7890', instructions: 'Bank Transfer via InstaPay/PESONet. Upload/keep receipt for verification.' }
};

// SVG Icon Component for exact container types
const GallonIcon = ({ type, className = "w-16 h-16 text-blue-500" }) => {
  if (type === 'round') {
    return (
      <svg className={className} viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2.5">
        <rect x="24" y="6" width="16" height="8" rx="2" className="fill-blue-100 dark:fill-blue-900" />
        <path d="M22 14h20v6L48 26v28a4 4 0 01-4 4H20a4 4 0 01-4-4V26l6-6v-6z" className="fill-blue-50/50 dark:fill-blue-950/50" />
        <line x1="16" y1="32" x2="48" y2="32" strokeDasharray="3 3" />
        <line x1="16" y1="42" x2="48" y2="42" strokeDasharray="3 3" />
      </svg>
    );
  }
  if (type === 'rect-faucet-half') {
    return (
      <svg className={className} viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2.5">
        <rect x="16" y="18" width="32" height="36" rx="4" className="fill-blue-50 dark:fill-blue-950" />
        <rect x="24" y="10" width="16" height="8" rx="2" className="fill-blue-200 dark:fill-blue-800" />
        <path d="M48 42h8v6h-8z" className="fill-amber-500" />
        <circle cx="52" cy="40" r="3" className="fill-amber-600" />
      </svg>
    );
  }
  // Default rect-faucet
  return (
    <svg className={className} viewBox="0 0 64 64" fill="none" stroke="currentColor" strokeWidth="2.5">
      <rect x="14" y="12" width="36" height="44" rx="4" className="fill-blue-50 dark:fill-blue-950" />
      <rect x="24" y="6" width="16" height="6" rx="2" className="fill-blue-200 dark:fill-blue-800" />
      <path d="M50 44h10v6h-10z" className="fill-amber-500" />
      <circle cx="55" cy="41" r="3" className="fill-amber-600" />
      <line x1="20" y1="24" x2="44" y2="24" strokeDasharray="2 2" />
    </svg>
  );
};

function App() {
  // Global State
  const [currentUser, setCurrentUser] = useState(null); // { id, name, email, phone, address, role }
  const [products, setProducts] = useState(INITIAL_PRODUCTS);
  const [orders, setOrders] = useState(INITIAL_ORDERS);
  const [paymentConfig, setPaymentConfig] = useState(INITIAL_PAYMENT_CONFIG);
  
  // Navigation State
  const [activeTab, setActiveTab] = useState('home'); // home, products, place_order, my_orders, my_profile, admin_dashboard, admin_orders, admin_products, admin_payments, setup_guide
  const [authMode, setAuthMode] = useState('login'); // login, register, admin_login
  
  // Cart State for Order Placement
  const [cart, setCart] = useState([]);
  const [orderSchedule, setOrderSchedule] = useState({ date: '', time: '09:00 AM - 11:00 AM' });
  const [orderDeliveryInstructions, setOrderDeliveryInstructions] = useState('');
  const [orderPaymentMethod, setOrderPaymentMethod] = useState('COD');
  const [checkoutStep, setCheckoutStep] = useState('cart'); // cart, delivery, review, success
  const [lastSubmittedOrderId, setLastSubmittedOrderId] = useState(null);

  // Filter States for Admin Order Table
  const [adminSearchQuery, setAdminSearchQuery] = useState('');
  const [adminStatusFilter, setAdminStatusFilter] = useState('ALL');

  // Form States
  const [authForm, setAuthForm] = useState({
    name: '', email: '', phone: '', password: '', address: 'Brgy. Sumacab Este, Cabanatuan City, Nueva Ecija'
  });
  
  const [editingProduct, setEditingProduct] = useState(null);
  const [newProductForm, setNewProductForm] = useState({
    name: '', category: 'refill', capacity: '20 Liters', price: 30, desc: '', image: 'rect-faucet'
  });

  const [cancellationModal, setCancellationModal] = useState({ open: false, orderId: null, reason: '' });
  const [rejectionModal, setRejectionModal] = useState({ open: false, orderId: null, reason: '' });

  // Pre-seed user credentials for easy demo login
  const handleQuickLogin = (role) => {
    if (role === 'customer') {
      setCurrentUser({
        id: 'cust1',
        name: 'Juan Dela Cruz',
        email: 'juan@gmail.com',
        phone: '09171234567',
        address: '123 Mabini St., Brgy. San Josef Sur, Cabanatuan City',
        role: 'customer'
      });
      setActiveTab('place_order');
    } else if (role === 'admin') {
      setCurrentUser({
        id: 'admin1',
        name: 'JP Refilling Admin',
        email: 'admin@jpwater.ph',
        role: 'admin'
      });
      setActiveTab('admin_dashboard');
    }
  };

  const handleLogout = () => {
    setCurrentUser(null);
    setActiveTab('home');
    setCart([]);
  };

  const handleAuthSubmit = (e) => {
    e.preventDefault();
    if (authMode === 'register') {
      const newUser = {
        id: 'cust_' + Date.now(),
        name: authForm.name,
        email: authForm.email,
        phone: authForm.phone,
        address: authForm.address,
        role: 'customer'
      };
      setCurrentUser(newUser);
      setActiveTab('place_order');
    } else if (authMode === 'login') {
      setCurrentUser({
        id: 'cust_' + Date.now(),
        name: authForm.name || 'Sample Customer',
        email: authForm.email,
        phone: authForm.phone || '09493608711',
        address: authForm.address || 'Cabanatuan City',
        role: 'customer'
      });
      setActiveTab('place_order');
    } else if (authMode === 'admin_login') {
      setCurrentUser({
        id: 'admin1',
        name: 'Authorized Administrator',
        email: authForm.email || 'admin@jpwater.ph',
        role: 'admin'
      });
      setActiveTab('admin_dashboard');
    }
  };

  // Cart operations
  const addToCart = (product) => {
    setCart(prev => {
      const existing = prev.find(item => item.productId === product.id);
      if (existing) {
        return prev.map(item => item.productId === product.id ? { ...item, quantity: item.quantity + 1 } : item);
      }
      return [...prev, {
        productId: product.id,
        name: product.name,
        capacity: product.capacity,
        unitPrice: product.price,
        quantity: 1
      }];
    });
  };

  const updateCartQty = (productId, delta) => {
    setCart(prev => prev.map(item => {
      if (item.productId === productId) {
        const newQty = item.quantity + delta;
        return newQty > 0 ? { ...item, quantity: newQty } : null;
      }
      return item;
    }).filter(Boolean));
  };

  const cartSubtotal = useMemo(() => {
    return cart.reduce((sum, item) => sum + (item.unitPrice * item.quantity), 0);
  }, [cart]);

  // Order submission
  const handlePlaceOrder = (e) => {
    e.preventDefault();
    if (cart.length === 0) return;

    const newOrderId = 'ORD-' + Math.floor(1000 + Math.random() * 9000);
    const newOrder = {
      id: newOrderId,
      customerId: currentUser ? currentUser.id : 'guest',
      customerName: currentUser ? currentUser.name : 'Walk-in / Online Guest',
      contactNumber: currentUser ? currentUser.phone : '09493608711',
      deliveryAddress: currentUser ? currentUser.address : 'Cabanatuan City',
      items: [...cart],
      totalAmount: cartSubtotal,
      paymentMethod: orderPaymentMethod,
      paymentStatus: 'Pending',
      orderStatus: 'Pending',
      orderDate: new Date().toLocaleString('en-US', { dateStyle: 'medium', timeStyle: 'short' }),
      requestedSchedule: { ...orderSchedule },
      confirmedSchedule: null,
      deliveryInstructions: orderDeliveryInstructions,
      cancellationReason: null
    };

    setOrders([newOrder, ...orders]);
    setCart([]);
    setLastSubmittedOrderId(newOrderId);
    setCheckoutStep('success');
  };

  // Customer Actions
  const handleCancelOrderSubmit = () => {
    setOrders(prev => prev.map(o => {
      if (o.id === cancellationModal.orderId) {
        return {
          ...o,
          orderStatus: 'Cancelled',
          cancellationReason: cancellationModal.reason || 'Cancelled by customer'
        };
      }
      return o;
    }));
    setCancellationModal({ open: false, orderId: null, reason: '' });
  };

  // Admin Actions
  const handleUpdateOrderStatus = (orderId, newStatus) => {
    setOrders(prev => prev.map(o => {
      if (o.id === orderId) {
        let updatedSchedule = o.confirmedSchedule;
        if (newStatus === 'Confirmed' && !updatedSchedule) {
          updatedSchedule = `${o.requestedSchedule.date} (${o.requestedSchedule.time})`;
        }
        return { ...o, orderStatus: newStatus, confirmedSchedule: updatedSchedule };
      }
      return o;
    }));
  };

  const handleUpdatePaymentStatus = (orderId, newPayStatus) => {
    setOrders(prev => prev.map(o => o.id === orderId ? { ...o, paymentStatus: newPayStatus } : o));
  };

  const handleAdminRejectOrder = () => {
    setOrders(prev => prev.map(o => {
      if (o.id === rejectionModal.orderId) {
        return {
          ...o,
          orderStatus: 'Cancelled',
          cancellationReason: rejectionModal.reason || 'Rejected by station management'
        };
      }
      return o;
    }));
    setRejectionModal({ open: false, orderId: null, reason: '' });
  };

  // Product Management Actions
  const handleToggleProductActive = (id) => {
    setProducts(prev => prev.map(p => p.id === id ? { ...p, active: !p.active } : p));
  };

  const handleSaveProduct = (e) => {
    e.preventDefault();
    if (editingProduct) {
      setProducts(prev => prev.map(p => p.id === editingProduct.id ? editingProduct : p));
      setEditingProduct(null);
    } else {
      const created = {
        id: 'p_' + Date.now(),
        ...newProductForm,
        price: Number(newProductForm.price),
        active: true
      };
      setProducts([...products, created]);
      setNewProductForm({ name: '', category: 'refill', capacity: '20 Liters', price: 30, desc: '', image: 'rect-faucet' });
    }
  };

  // Filtered orders for admin
  const filteredOrders = useMemo(() => {
    return orders.filter(o => {
      const matchesSearch = o.id.toLowerCase().includes(adminSearchQuery.toLowerCase()) || 
                            o.customerName.toLowerCase().includes(adminSearchQuery.toLowerCase()) ||
                            o.contactNumber.includes(adminSearchQuery);
      const matchesStatus = adminStatusFilter === 'ALL' || o.orderStatus === adminStatusFilter;
      return matchesSearch && matchesStatus;
    });
  }, [orders, adminSearchQuery, adminStatusFilter]);

  // Admin Sales Statistics
  const adminStats = useMemo(() => {
    const total = orders.length;
    const pending = orders.filter(o => o.orderStatus === 'Pending').length;
    const confirmed = orders.filter(o => o.orderStatus === 'Confirmed').length;
    const preparing = orders.filter(o => o.orderStatus === 'Preparing').length;
    const outForDelivery = orders.filter(o => o.orderStatus === 'Out for Delivery').length;
    const delivered = orders.filter(o => o.orderStatus === 'Delivered').length;
    const cancelled = orders.filter(o => o.orderStatus === 'Cancelled').length;
    const totalSales = orders.filter(o => o.orderStatus === 'Delivered').reduce((sum, o) => sum + o.totalAmount, 0);

    return { total, pending, confirmed, preparing, outForDelivery, delivered, cancelled, totalSales };
  }, [orders]);

  return (
    <div className="min-h-screen bg-slate-50 text-slate-800 font-sans flex flex-col">
      
      {/* QUICK ROLE SWITCHER BANNER */}
      <div className="bg-blue-900 text-white text-xs px-4 py-2 flex flex-wrap justify-between items-center gap-2">
        <div className="flex items-center gap-2">
          <span className="font-bold bg-blue-700 px-2 py-0.5 rounded text-[10px] uppercase tracking-wider">Demo Quick Access</span>
          <span>Switch Roles instantly to test system functionality:</span>
        </div>
        <div className="flex items-center gap-3">
          <button 
            onClick={() => handleQuickLogin('customer')}
            className={`px-3 py-1 rounded transition font-medium ${currentUser?.role === 'customer' ? 'bg-blue-500 text-white' : 'bg-blue-800 hover:bg-blue-700'}`}
          >
            👤 Log in as Customer
          </button>
          <button 
            onClick={() => handleQuickLogin('admin')}
            className={`px-3 py-1 rounded transition font-medium ${currentUser?.role === 'admin' ? 'bg-emerald-600 text-white' : 'bg-blue-800 hover:bg-blue-700'}`}
          >
            🛡️ Log in as Administrator
          </button>
          {currentUser && (
            <button onClick={handleLogout} className="text-slate-300 hover:text-white underline ml-2">
              Logout
            </button>
          )}
        </div>
      </div>

      {/* HEADER & NAVIGATION BAR */}
      <header className="bg-white border-b border-slate-200 sticky top-0 z-40 shadow-sm">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex justify-between items-center h-20">
          
          {/* Business Logo & Name */}
          <div className="flex items-center gap-3 cursor-pointer" onClick={() => setActiveTab('home')}>
            <div className="w-12 h-12 rounded-xl bg-gradient-to-tr from-blue-600 to-cyan-500 flex items-center justify-center text-white shadow-md shadow-blue-500/20">
              <Droplet className="w-7 h-7 fill-white" />
            </div>
            <div>
              <h1 className="text-2xl font-black tracking-tight text-blue-950 uppercase">JP WATER REFILLING</h1>
              <p className="text-xs font-semibold text-blue-600 tracking-wider uppercase">Cabanatuan City • Purified Drinking Water</p>
            </div>
          </div>

          {/* Nav Items */}
          <nav className="hidden md:flex items-center gap-1">
            {/* PUBLIC / CUSTOMER LINKS */}
            {(!currentUser || currentUser.role === 'customer') && (
              <>
                <button onClick={() => setActiveTab('home')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${activeTab === 'home' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600 hover:bg-slate-50'}`}>
                  Home
                </button>
                <button onClick={() => setActiveTab('products')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${activeTab === 'products' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600 hover:bg-slate-50'}`}>
                  Products & Pricing
                </button>
                
                {currentUser && (
                  <>
                    <button onClick={() => setActiveTab('place_order')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition flex items-center gap-2 ${activeTab === 'place_order' ? 'bg-blue-600 text-white shadow-sm' : 'text-slate-600 hover:text-blue-600 hover:bg-slate-50'}`}>
                      <ShoppingBag className="w-4 h-4" /> Place an Order
                      {cart.length > 0 && <span className="bg-amber-400 text-slate-900 text-xs px-2 py-0.5 rounded-full font-bold">{cart.length}</span>}
                    </button>
                    <button onClick={() => setActiveTab('my_orders')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${activeTab === 'my_orders' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600 hover:bg-slate-50'}`}>
                      My Orders
                    </button>
                    <button onClick={() => setActiveTab('my_profile')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${activeTab === 'my_profile' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600 hover:bg-slate-50'}`}>
                      My Profile
                    </button>
                  </>
                )}
              </>
            )}

            {/* ADMIN LINKS */}
            {currentUser?.role === 'admin' && (
              <>
                <button onClick={() => setActiveTab('admin_dashboard')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${activeTab === 'admin_dashboard' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600'}`}>
                  Dashboard
                </button>
                <button onClick={() => setActiveTab('admin_orders')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition relative ${activeTab === 'admin_orders' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600'}`}>
                  Orders
                  {adminStats.pending > 0 && (
                    <span className="ml-1.5 bg-rose-500 text-white text-xs px-1.5 py-0.5 rounded-full font-bold">{adminStats.pending}</span>
                  )}
                </button>
                <button onClick={() => setActiveTab('admin_products')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${activeTab === 'admin_products' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600'}`}>
                  Product Catalog
                </button>
                <button onClick={() => setActiveTab('admin_payments')} className={`px-4 py-2 rounded-lg text-sm font-semibold transition ${activeTab === 'admin_payments' ? 'bg-blue-50 text-blue-700' : 'text-slate-600 hover:text-blue-600'}`}>
                  Payment Settings
                </button>
              </>
            )}

            <button onClick={() => setActiveTab('setup_guide')} className={`px-3 py-2 rounded-lg text-xs font-semibold text-slate-500 border border-slate-200 hover:bg-slate-100 ${activeTab === 'setup_guide' ? 'bg-slate-200 font-bold' : ''}`}>
              ⚙️ DB Setup
            </button>
          </nav>

          {/* User Auth Controls */}
          <div className="flex items-center gap-3">
            {!currentUser ? (
              <div className="flex gap-2">
                <button 
                  onClick={() => { setAuthMode('login'); setActiveTab('auth'); }}
                  className="px-4 py-2 text-sm font-semibold text-blue-600 bg-blue-50 rounded-lg hover:bg-blue-100 transition"
                >
                  Customer Login
                </button>
                <button 
                  onClick={() => { setAuthMode('admin_login'); setActiveTab('auth'); }}
                  className="px-4 py-2 text-sm font-semibold text-slate-700 border border-slate-300 rounded-lg hover:bg-slate-50 transition flex items-center gap-1.5"
                >
                  <Shield className="w-4 h-4 text-slate-500" /> Admin
                </button>
              </div>
            ) : (
              <div className="flex items-center gap-3 bg-slate-100 pl-3 pr-2 py-1.5 rounded-xl border border-slate-200">
                <div className="text-right">
                  <p className="text-xs font-bold text-slate-800 leading-tight">{currentUser.name}</p>
                  <span className={`text-[10px] font-bold uppercase tracking-wider ${currentUser.role === 'admin' ? 'text-emerald-600' : 'text-blue-600'}`}>
                    {currentUser.role}
                  </span>
                </div>
                <button 
                  onClick={handleLogout}
                  title="Logout"
                  className="p-1.5 text-slate-400 hover:text-rose-600 hover:bg-white rounded-lg transition"
                >
                  <LogOut className="w-4 h-4" />
                </button>
              </div>
            )}
          </div>

        </div>
      </header>

      {/* MAIN CONTENT CONTAINER */}
      <main className="flex-1 max-w-7xl w-full mx-auto px-4 sm:px-6 lg:px-8 py-8">
        
        {/* ==================== HOMEPAGE ==================== */}
        {activeTab === 'home' && (
          <div className="space-y-12">
            
            {/* HERO SECTION */}
            <div className="bg-gradient-to-r from-blue-700 via-blue-600 to-cyan-600 rounded-3xl text-white p-8 sm:p-12 shadow-xl shadow-blue-600/15 relative overflow-hidden">
              <div className="max-w-2xl relative z-10 space-y-6">
                <span className="bg-blue-500/40 text-blue-100 font-semibold text-xs px-3.5 py-1.5 rounded-full border border-blue-300/30 tracking-wide uppercase">
                  📍 Serving Cabanatuan City, Nueva Ecija
                </span>
                <h1 className="text-4xl sm:text-5xl font-black tracking-tight leading-tight">
                  Clean, Safe & Purified Drinking Water Delivered Right to Your Door.
                </h1>
                <p className="text-blue-100 text-lg">
                  Fast, reliable water refilling, new gallon purchases, and replacement containers for households, offices, and commercial establishments.
                </p>
                <div className="flex flex-wrap gap-4 pt-2">
                  <button 
                    onClick={() => {
                      if (!currentUser) handleQuickLogin('customer');
                      else setActiveTab('place_order');
                    }}
                    className="bg-amber-400 hover:bg-amber-300 text-slate-950 font-bold px-6 py-3.5 rounded-xl shadow-lg transition flex items-center gap-2"
                  >
                    <ShoppingBag className="w-5 h-5" /> Order Water Refill Now
                  </button>
                  <button 
                    onClick={() => setActiveTab('products')}
                    className="bg-white/10 hover:bg-white/20 text-white font-semibold px-6 py-3.5 rounded-xl backdrop-blur transition"
                  >
                    View Product Catalog & Prices
                  </button>
                </div>
              </div>

              <div className="absolute right-[-20px] bottom-[-20px] opacity-20 pointer-events-none hidden lg:block">
                <Droplet className="w-96 h-96 text-white" />
              </div>
            </div>

            {/* SERVICE INFORMATION SUMMARY */}
            <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
              <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm flex items-start gap-4">
                <div className="p-3 bg-blue-50 rounded-xl text-blue-600">
                  <MapPin className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="font-bold text-slate-900">Coverage Area</h3>
                  <p className="text-sm text-slate-600 mt-1">Cabanatuan City, Nueva Ecija and nearby barangays with scheduled morning & afternoon slots.</p>
                </div>
              </div>

              <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm flex items-start gap-4">
                <div className="p-3 bg-blue-50 rounded-xl text-blue-600">
                  <Phone className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="font-bold text-slate-900">Direct Contact Hotlines</h3>
                  <p className="text-sm text-slate-700 font-semibold mt-1">0949-360-8711</p>
                  <p className="text-sm text-slate-700 font-semibold">0908-298-0925</p>
                </div>
              </div>

              <div className="bg-white p-6 rounded-2xl border border-slate-200 shadow-sm flex items-start gap-4">
                <div className="p-3 bg-blue-50 rounded-xl text-blue-600">
                  <CreditCard className="w-6 h-6" />
                </div>
                <div>
                  <h3 className="font-bold text-slate-900">Payment Options</h3>
                  <p className="text-sm text-slate-600 mt-1">Cash on Delivery (COD), GCash, Maya Wallet, and Online Bank Transfer.</p>
                </div>
              </div>
            </div>

            {/* FEATURED PRODUCTS SUMMARY */}
            <div>
              <div className="flex justify-between items-end mb-6">
                <div>
                  <h2 className="text-2xl font-bold text-slate-900">Standard Product Offerings</h2>
                  <p className="text-slate-500 text-sm">Affordable water refills and containers with transparent pricing.</p>
                </div>
                <button onClick={() => setActiveTab('products')} className="text-blue-600 hover:text-blue-700 font-bold text-sm">
                  Full Catalog &rarr;
                </button>
              </div>

              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {products.slice(0, 3).map(product => (
                  <div key={product.id} className="bg-white rounded-2xl border border-slate-200 p-6 flex flex-col justify-between hover:shadow-md transition">
                    <div>
                      <div className="flex items-center justify-between mb-4">
                        <span className="bg-blue-100 text-blue-800 text-xs font-bold px-2.5 py-1 rounded-full uppercase">
                          Refill
                        </span>
                        <span className="text-2xl font-black text-blue-600">₱{product.price}</span>
                      </div>
                      <div className="flex justify-center my-4">
                        <GallonIcon type={product.image} />
                      </div>
                      <h3 className="font-bold text-slate-900 text-lg leading-snug">{product.name}</h3>
                      <p className="text-xs text-slate-500 font-medium mt-1">Capacity: {product.capacity}</p>
                      <p className="text-sm text-slate-600 mt-3">{product.desc}</p>
                    </div>
                    <button 
                      onClick={() => {
                        addToCart(product);
                        if (!currentUser) handleQuickLogin('customer');
                        else setActiveTab('place_order');
                      }}
                      className="mt-6 w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-sm transition"
                    >
                      + Order Refill
                    </button>
                  </div>
                ))}
              </div>
            </div>

          </div>
        )}

        {/* ==================== PRODUCT CATALOG PAGE ==================== */}
        {activeTab === 'products' && (
          <div className="space-y-8">
            <div>
              <h2 className="text-3xl font-extrabold text-slate-900">Product Catalog & Pricing</h2>
              <p className="text-slate-600 text-sm mt-1">Select products to add directly to your water delivery order.</p>
            </div>

            {/* A. WATER REFILLS */}
            <div className="space-y-4">
              <div className="border-b border-slate-200 pb-2 flex items-center gap-2">
                <Droplet className="w-5 h-5 text-blue-600" />
                <h3 className="text-xl font-bold text-slate-900">A. Water Refills</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {products.filter(p => p.category === 'refill' && p.active).map(product => (
                  <div key={product.id} className="bg-white rounded-2xl border border-slate-200 p-6 flex flex-col justify-between shadow-sm">
                    <div>
                      <div className="flex justify-between items-start mb-2">
                        <GallonIcon type={product.image} />
                        <span className="text-3xl font-black text-blue-600">₱{product.price}</span>
                      </div>
                      <h4 className="font-bold text-slate-900 text-lg mt-2">{product.name}</h4>
                      <p className="text-xs font-semibold text-blue-600 mt-0.5">Capacity: {product.capacity}</p>
                      <p className="text-sm text-slate-500 mt-2">{product.desc}</p>
                    </div>
                    <button 
                      onClick={() => {
                        addToCart(product);
                        if (!currentUser) handleQuickLogin('customer');
                        else setActiveTab('place_order');
                      }}
                      className="mt-6 w-full py-2.5 bg-blue-600 hover:bg-blue-700 text-white rounded-xl font-bold text-sm transition flex items-center justify-center gap-2"
                    >
                      <Plus className="w-4 h-4" /> Add to Order
                    </button>
                  </div>
                ))}
              </div>
            </div>

            {/* B. EMPTY GALLONS ONLY */}
            <div className="space-y-4 pt-4">
              <div className="border-b border-slate-200 pb-2 flex items-center gap-2">
                <ShoppingBag className="w-5 h-5 text-slate-600" />
                <h3 className="text-xl font-bold text-slate-900">B. Empty Gallons Only</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {products.filter(p => p.category === 'empty' && p.active).map(product => (
                  <div key={product.id} className="bg-white rounded-2xl border border-slate-200 p-6 flex flex-col justify-between shadow-sm">
                    <div>
                      <div className="flex justify-between items-start mb-2">
                        <GallonIcon type={product.image} />
                        <span className="text-3xl font-black text-slate-800">₱{product.price}</span>
                      </div>
                      <h4 className="font-bold text-slate-900 text-lg mt-2">{product.name}</h4>
                      <p className="text-xs font-semibold text-slate-500 mt-0.5">Capacity: {product.capacity}</p>
                      <p className="text-sm text-slate-500 mt-2">{product.desc}</p>
                    </div>
                    <button 
                      onClick={() => {
                        addToCart(product);
                        if (!currentUser) handleQuickLogin('customer');
                        else setActiveTab('place_order');
                      }}
                      className="mt-6 w-full py-2.5 bg-slate-800 hover:bg-slate-900 text-white rounded-xl font-bold text-sm transition flex items-center justify-center gap-2"
                    >
                      <Plus className="w-4 h-4" /> Add to Order
                    </button>
                  </div>
                ))}
              </div>
            </div>

            {/* C. NEW GALLON WITH WATER */}
            <div className="space-y-4 pt-4">
              <div className="border-b border-slate-200 pb-2 flex items-center gap-2">
                <CheckCircle className="w-5 h-5 text-emerald-600" />
                <h3 className="text-xl font-bold text-slate-900">C. New Gallon with Purified Water</h3>
              </div>
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                {products.filter(p => p.category === 'new_with_water' && p.active).map(product => (
                  <div key={product.id} className="bg-white rounded-2xl border border-slate-200 p-6 flex flex-col justify-between shadow-sm">
                    <div>
                      <div className="flex justify-between items-start mb-2">
                        <GallonIcon type={product.image} />
                        <span className="text-3xl font-black text-emerald-600">₱{product.price}</span>
                      </div>
                      <h4 className="font-bold text-slate-900 text-lg mt-2">{product.name}</h4>
                      <p className="text-xs font-semibold text-emerald-600 mt-0.5">Capacity: {product.capacity}</p>
                      <p className="text-sm text-slate-500 mt-2">{product.desc}</p>
                    </div>
                    <button 
                      onClick={() => {
                        addToCart(product);
                        if (!currentUser) handleQuickLogin('customer');
                        else setActiveTab('place_order');
                      }}
                      className="mt-6 w-full py-2.5 bg-emerald-600 hover:bg-emerald-700 text-white rounded-xl font-bold text-sm transition flex items-center justify-center gap-2"
                    >
                      <Plus className="w-4 h-4" /> Add to Order
                    </button>
                  </div>
                ))}
              </div>
            </div>

          </div>
        )}

        {/* ==================== CUSTOMER AUTHENTICATION ==================== */}
        {activeTab === 'auth' && (
          <div className="max-w-md mx-auto bg-white rounded-2xl border border-slate-200 shadow-lg p-8">
            <div className="text-center mb-6">
              <div className="w-12 h-12 bg-blue-100 text-blue-600 rounded-xl flex items-center justify-center mx-auto mb-2">
                <Droplet className="w-6 h-6" />
              </div>
              <h2 className="text-2xl font-bold text-slate-900">
                {authMode === 'login' && 'Customer Login'}
                {authMode === 'register' && 'Create Customer Account'}
                {authMode === 'admin_login' && 'Administrator Portal'}
              </h2>
              <p className="text-xs text-slate-500 mt-1">
                {authMode === 'admin_login' ? 'Restricted to authorized staff accounts.' : 'Manage your orders and delivery preferences.'}
              </p>
            </div>

            <form onSubmit={handleAuthSubmit} className="space-y-4">
              {authMode === 'register' && (
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Full Name</label>
                  <input 
                    type="text" 
                    required 
                    placeholder="Juan Dela Cruz"
                    value={authForm.name} 
                    onChange={e => setAuthForm({ ...authForm, name: e.target.value })}
                    className="w-full px-3.5 py-2.5 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                  />
                </div>
              )}

              <div>
                <label className="block text-xs font-bold text-slate-700 uppercase mb-1">
                  {authMode === 'admin_login' ? 'Admin Username or Email' : 'Email Address'}
                </label>
                <input 
                  type="email" 
                  required 
                  placeholder={authMode === 'admin_login' ? 'admin@jpwater.ph' : 'juan@gmail.com'}
                  value={authForm.email} 
                  onChange={e => setAuthForm({ ...authForm, email: e.target.value })}
                  className="w-full px-3.5 py-2.5 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                />
              </div>

              {authMode === 'register' && (
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Contact Number</label>
                  <input 
                    type="text" 
                    required 
                    placeholder="09171234567"
                    value={authForm.phone} 
                    onChange={e => setAuthForm({ ...authForm, phone: e.target.value })}
                    className="w-full px-3.5 py-2.5 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                  />
                </div>
              )}

              {authMode === 'register' && (
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Complete Delivery Address (Cabanatuan City)</label>
                  <textarea 
                    rows={2} 
                    required 
                    placeholder="House No., Street Name, Barangay, Cabanatuan City"
                    value={authForm.address} 
                    onChange={e => setAuthForm({ ...authForm, address: e.target.value })}
                    className="w-full px-3.5 py-2.5 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                  />
                </div>
              )}

              <div>
                <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Password</label>
                <input 
                  type="password" 
                  required 
                  placeholder="••••••••"
                  value={authForm.password} 
                  onChange={e => setAuthForm({ ...authForm, password: e.target.value })}
                  className="w-full px-3.5 py-2.5 border border-slate-300 rounded-lg text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                />
              </div>

              <button 
                type="submit" 
                className="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl shadow-md transition text-sm mt-2"
              >
                {authMode === 'login' && 'Sign In to Account'}
                {authMode === 'register' && 'Register Account'}
                {authMode === 'admin_login' && 'Authenticate Administrator'}
              </button>
            </form>

            <div className="mt-6 pt-4 border-t border-slate-200 text-center text-xs text-slate-600 space-y-2">
              {authMode === 'login' && (
                <p>Don't have an account? <button onClick={() => setAuthMode('register')} className="text-blue-600 font-bold underline">Register Here</button></p>
              )}
              {authMode === 'register' && (
                <p>Already have an account? <button onClick={() => setAuthMode('login')} className="text-blue-600 font-bold underline">Sign In</button></p>
              )}
              {authMode === 'admin_login' && (
                <p className="text-amber-700 font-medium">⚠️ Note: Customer account creation never grants administrator access.</p>
              )}
            </div>
          </div>
        )}

        {/* ==================== PLACE AN ORDER (CUSTOMER WORKFLOW) ==================== */}
        {activeTab === 'place_order' && (
          <div className="space-y-8">
            <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
              <div>
                <h2 className="text-3xl font-extrabold text-slate-900">Place Water Order</h2>
                <p className="text-slate-500 text-sm">Select products, set delivery date, and complete order checkout.</p>
              </div>
              <div className="flex items-center gap-2 bg-blue-50 text-blue-700 px-4 py-2 rounded-xl text-xs font-bold border border-blue-200">
                <span>Deliver To:</span>
                <span className="text-slate-800">{currentUser?.address || 'Cabanatuan City'}</span>
              </div>
            </div>

            {checkoutStep === 'cart' && (
              <div className="grid grid-cols-1 lg:grid-cols-3 gap-8">
                
                {/* Available Catalog Picker */}
                <div className="lg:col-span-2 space-y-4">
                  <h3 className="font-bold text-slate-900 text-lg">Select Items from Catalog</h3>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    {products.filter(p => p.active).map(product => (
                      <div key={product.id} className="bg-white p-4 rounded-xl border border-slate-200 flex items-center justify-between shadow-sm">
                        <div className="flex items-center gap-3">
                          <GallonIcon type={product.image} className="w-10 h-10 text-blue-600" />
                          <div>
                            <h4 className="font-bold text-sm text-slate-900 leading-tight">{product.name}</h4>
                            <span className="text-xs font-extrabold text-blue-600">₱{product.price}</span>
                            <span className="text-[11px] text-slate-400 ml-2">({product.capacity})</span>
                          </div>
                        </div>
                        <button 
                          onClick={() => addToCart(product)}
                          className="px-3 py-1.5 bg-blue-600 hover:bg-blue-700 text-white font-bold text-xs rounded-lg transition"
                        >
                          + Add
                        </button>
                      </div>
                    ))}
                  </div>
                </div>

                {/* Cart Summary Panel */}
                <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm h-fit space-y-6">
                  <h3 className="font-bold text-slate-900 text-lg border-b border-slate-200 pb-3 flex items-center justify-between">
                    <span>Order Cart</span>
                    <span className="text-xs bg-slate-100 text-slate-700 px-2 py-0.5 rounded-full">{cart.length} items</span>
                  </h3>

                  {cart.length === 0 ? (
                    <div className="text-center py-8 text-slate-400 text-sm">
                      Your order cart is empty. Please add water refills or gallons above.
                    </div>
                  ) : (
                    <div className="space-y-4">
                      {cart.map(item => (
                        <div key={item.productId} className="flex justify-between items-center text-sm border-b border-slate-100 pb-3">
                          <div className="flex-1 pr-2">
                            <p className="font-semibold text-slate-800 leading-tight">{item.name}</p>
                            <p className="text-xs text-slate-500">₱{item.unitPrice} each</p>
                          </div>
                          <div className="flex items-center gap-2">
                            <button onClick={() => updateCartQty(item.productId, -1)} className="w-6 h-6 bg-slate-100 hover:bg-slate-200 rounded font-bold text-slate-700 text-xs">-</button>
                            <span className="font-bold w-4 text-center">{item.quantity}</span>
                            <button onClick={() => updateCartQty(item.productId, 1)} className="w-6 h-6 bg-slate-100 hover:bg-slate-200 rounded font-bold text-slate-700 text-xs">+</button>
                          </div>
                          <span className="font-bold text-slate-900 ml-3 min-w-[50px] text-right">₱{item.unitPrice * item.quantity}</span>
                        </div>
                      ))}

                      <div className="pt-2 border-t border-slate-200">
                        <div className="flex justify-between text-base font-extrabold text-slate-900">
                          <span>Total Amount</span>
                          <span className="text-blue-600 text-xl">₱{cartSubtotal}</span>
                        </div>
                      </div>

                      <button 
                        onClick={() => setCheckoutStep('delivery')}
                        className="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl shadow transition text-sm flex items-center justify-center gap-2"
                      >
                        Proceed to Schedule & Payment &rarr;
                      </button>
                    </div>
                  )}
                </div>

              </div>
            )}

            {/* Step 2: Delivery Details & Payment */}
            {checkoutStep === 'delivery' && (
              <form onSubmit={handlePlaceOrder} className="max-w-3xl mx-auto bg-white rounded-2xl border border-slate-200 shadow-md p-8 space-y-6">
                <div className="border-b border-slate-200 pb-4">
                  <h3 className="text-2xl font-bold text-slate-900">Delivery & Payment Preferences</h3>
                  <p className="text-xs text-slate-500 mt-1">Provide your delivery slot preference and payment selection.</p>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                  <div>
                    <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Preferred Delivery Date</label>
                    <input 
                      type="date" 
                      required 
                      value={orderSchedule.date} 
                      onChange={e => setOrderSchedule({ ...orderSchedule, date: e.target.value })}
                      className="w-full px-3.5 py-2.5 border border-slate-300 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 outline-none" 
                    />
                  </div>

                  <div>
                    <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Preferred Time Window</label>
                    <select 
                      value={orderSchedule.time} 
                      onChange={e => setOrderSchedule({ ...orderSchedule, time: e.target.value })}
                      className="w-full px-3.5 py-2.5 border border-slate-300 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 outline-none bg-white"
                    >
                      <option value="08:00 AM - 10:00 AM">08:00 AM - 10:00 AM</option>
                      <option value="10:00 AM - 12:00 PM">10:00 AM - 12:00 PM</option>
                      <option value="01:00 PM - 03:00 PM">01:00 PM - 03:00 PM</option>
                      <option value="03:00 PM - 05:00 PM">03:00 PM - 05:00 PM</option>
                    </select>
                  </div>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Delivery Instructions / Landmarks (Optional)</label>
                  <textarea 
                    rows={2}
                    placeholder="e.g. Beside Barangay Hall, Gate is color blue"
                    value={orderDeliveryInstructions}
                    onChange={e => setOrderDeliveryInstructions(e.target.value)}
                    className="w-full px-3.5 py-2.5 border border-slate-300 rounded-xl text-sm focus:ring-2 focus:ring-blue-500 outline-none"
                  />
                </div>

                {/* Payment Selection */}
                <div className="space-y-3 pt-2">
                  <label className="block text-xs font-bold text-slate-700 uppercase">Select Payment Method</label>
                  <div className="grid grid-cols-2 sm:grid-cols-4 gap-3">
                    {[
                      { id: 'COD', label: 'Cash on Delivery', sub: 'Pay cash to rider' },
                      { id: 'GCash', label: 'GCash', sub: 'E-Wallet Transfer' },
                      { id: 'Maya', label: 'Maya', sub: 'E-Wallet Transfer' },
                      { id: 'Bank', label: 'Bank Transfer', sub: 'InstaPay / BDO' }
                    ].map(pm => (
                      <button
                        key={pm.id}
                        type="button"
                        onClick={() => setOrderPaymentMethod(pm.id)}
                        className={`p-3 rounded-xl border text-left transition ${orderPaymentMethod === pm.id ? 'border-blue-600 bg-blue-50/50 ring-2 ring-blue-500' : 'border-slate-200 hover:border-slate-300'}`}
                      >
                        <p className="font-bold text-sm text-slate-900">{pm.label}</p>
                        <p className="text-[10px] text-slate-500 mt-0.5">{pm.sub}</p>
                      </button>
                    ))}
                  </div>

                  {/* Configured Payment Instructions Box */}
                  {orderPaymentMethod !== 'COD' && (
                    <div className="mt-3 p-4 bg-slate-50 border border-slate-200 rounded-xl text-xs text-slate-700 space-y-1">
                      <p className="font-bold text-slate-900 uppercase">
                        {paymentConfig[orderPaymentMethod.toLowerCase()]?.title || orderPaymentMethod} Payment Instructions:
                      </p>
                      <p>Account Name: <span className="font-bold">{paymentConfig[orderPaymentMethod.toLowerCase()]?.accountName}</span></p>
                      <p>Account Number: <span className="font-bold">{paymentConfig[orderPaymentMethod.toLowerCase()]?.accountNumber}</span></p>
                      <p className="text-slate-500 italic mt-1">{paymentConfig[orderPaymentMethod.toLowerCase()]?.instructions}</p>
                      <p className="text-[11px] text-amber-700 bg-amber-50 p-2 rounded border border-amber-200 mt-2 font-medium">
                        ⓘ Note: Selecting an e-wallet or bank transfer reserves your order. Payment status will remain <strong>Pending Verification</strong> until validated by administrator.
                      </p>
                    </div>
                  )}
                </div>

                {/* Final Order Review & Disclaimer */}
                <div className="bg-slate-50 p-4 rounded-xl border border-slate-200 space-y-2">
                  <div className="flex justify-between items-center text-sm font-bold text-slate-900">
                    <span>Order Total ({cart.length} items):</span>
                    <span className="text-blue-600 text-lg">₱{cartSubtotal}</span>
                  </div>
                  <p className="text-[11px] text-slate-500 leading-relaxed">
                    ℹ️ <strong>Delivery Disclaimer:</strong> The requested delivery date and time are preferences. Final schedule will be confirmed by the station administrator upon order approval.
                  </p>
                </div>

                <div className="flex gap-3">
                  <button 
                    type="button" 
                    onClick={() => setCheckoutStep('cart')}
                    className="w-1/3 py-3 border border-slate-300 text-slate-700 font-bold rounded-xl hover:bg-slate-50 transition text-sm"
                  >
                    Back to Cart
                  </button>
                  <button 
                    type="submit" 
                    className="w-2/3 py-3 bg-emerald-600 hover:bg-emerald-700 text-white font-bold rounded-xl shadow-md transition text-sm"
                  >
                    Submit Water Order
                  </button>
                </div>
              </form>
            )}

            {/* Step 3: Success Confirmation */}
            {checkoutStep === 'success' && (
              <div className="max-w-md mx-auto bg-white rounded-2xl border border-slate-200 shadow-xl p-8 text-center space-y-4">
                <div className="w-16 h-16 bg-emerald-100 text-emerald-600 rounded-full flex items-center justify-center mx-auto">
                  <CheckCircle className="w-10 h-10" />
                </div>
                <h3 className="text-2xl font-black text-slate-900">Order Submitted!</h3>
                <p className="text-sm text-slate-600">
                  Your order reference is <strong className="text-blue-600">{lastSubmittedOrderId}</strong>.
                </p>
                <div className="p-4 bg-amber-50 border border-amber-200 rounded-xl text-left text-xs text-amber-900 space-y-1">
                  <p className="font-bold">Important Notice:</p>
                  <p>Your requested delivery date & time are preferences and are not final until confirmed by JP Water Refilling administrator.</p>
                </div>
                <button 
                  onClick={() => { setCheckoutStep('cart'); setActiveTab('my_orders'); }}
                  className="w-full py-3 bg-blue-600 hover:bg-blue-700 text-white font-bold rounded-xl shadow transition text-sm"
                >
                  View My Orders & Status
                </button>
              </div>
            )}

          </div>
        )}

        {/* ==================== CUSTOMER ORDER HISTORY ==================== */}
        {activeTab === 'my_orders' && (
          <div className="space-y-6">
            <div>
              <h2 className="text-3xl font-extrabold text-slate-900">My Water Orders</h2>
              <p className="text-slate-500 text-sm">Track your refill delivery status and order history.</p>
            </div>

            {orders.filter(o => o.customerId === currentUser?.id || o.customerId === 'cust1').length === 0 ? (
              <div className="bg-white rounded-2xl border border-slate-200 p-12 text-center text-slate-400">
                <ShoppingBag className="w-12 h-12 mx-auto mb-3 text-slate-300" />
                <p className="font-bold text-slate-600">No orders placed yet.</p>
                <p className="text-xs mt-1">Place your first order for fresh purified drinking water.</p>
                <button onClick={() => setActiveTab('place_order')} className="mt-4 px-4 py-2 bg-blue-600 text-white rounded-xl font-bold text-xs">
                  Place an Order Now
                </button>
              </div>
            ) : (
              <div className="space-y-4">
                {orders.filter(o => o.customerId === currentUser?.id || o.customerId === 'cust1').map(order => (
                  <div key={order.id} className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm space-y-4">
                    
                    <div className="flex flex-wrap justify-between items-start gap-2 border-b border-slate-100 pb-3">
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-black text-lg text-slate-900">{order.id}</span>
                          <span className="text-xs text-slate-400">• {order.orderDate}</span>
                        </div>
                        <p className="text-xs text-slate-500 mt-0.5">Address: {order.deliveryAddress}</p>
                      </div>

                      {/* Status Badges */}
                      <div className="flex items-center gap-2">
                        <span className={`px-3 py-1 rounded-full text-xs font-bold uppercase tracking-wider ${
                          order.orderStatus === 'Pending' ? 'bg-amber-100 text-amber-800' :
                          order.orderStatus === 'Confirmed' ? 'bg-blue-100 text-blue-800' :
                          order.orderStatus === 'Preparing' ? 'bg-purple-100 text-purple-800' :
                          order.orderStatus === 'Out for Delivery' ? 'bg-cyan-100 text-cyan-800' :
                          order.orderStatus === 'Delivered' ? 'bg-emerald-100 text-emerald-800' :
                          'bg-rose-100 text-rose-800'
                        }`}>
                          {order.orderStatus}
                        </span>
                      </div>
                    </div>

                    {/* Order Details Grid */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs">
                      
                      {/* Products */}
                      <div className="bg-slate-50 p-3 rounded-xl border border-slate-100">
                        <p className="font-bold text-slate-700 uppercase text-[10px] mb-1">Ordered Products</p>
                        <ul className="space-y-1">
                          {order.items.map((it, idx) => (
                            <li key={idx} className="flex justify-between text-slate-800">
                              <span>{it.quantity}x {it.name}</span>
                              <span className="font-bold">₱{it.unitPrice * it.quantity}</span>
                            </li>
                          ))}
                        </ul>
                        <div className="mt-2 pt-2 border-t border-slate-200 flex justify-between font-extrabold text-slate-900 text-sm">
                          <span>Total Amount</span>
                          <span className="text-blue-600">₱{order.totalAmount}</span>
                        </div>
                      </div>

                      {/* Schedule Info */}
                      <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 space-y-1">
                        <p className="font-bold text-slate-700 uppercase text-[10px]">Schedule Details</p>
                        <p className="text-slate-600">
                          Requested Slot: <span className="font-medium text-slate-900">{order.requestedSchedule.date} ({order.requestedSchedule.time})</span>
                        </p>
                        <p className="text-slate-600">
                          Confirmed Slot:{' '}
                          {order.confirmedSchedule ? (
                            <span className="font-bold text-emerald-700">{order.confirmedSchedule}</span>
                          ) : (
                            <span className="text-amber-600 italic">Pending Admin Confirmation</span>
                          )}
                        </p>
                        {order.deliveryInstructions && (
                          <p className="text-slate-500 italic text-[11px] mt-1">Note: "{order.deliveryInstructions}"</p>
                        )}
                      </div>

                      {/* Payment & Actions */}
                      <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 flex flex-col justify-between">
                        <div>
                          <p className="font-bold text-slate-700 uppercase text-[10px]">Payment Info</p>
                          <p className="text-slate-800 font-semibold">{order.paymentMethod}</p>
                          <span className={`inline-block mt-1 px-2 py-0.5 text-[10px] rounded font-bold ${
                            order.paymentStatus === 'Verified' ? 'bg-emerald-100 text-emerald-800' : 'bg-amber-100 text-amber-800'
                          }`}>
                            Payment Status: {order.paymentStatus}
                          </span>
                        </div>

                        {/* Customer Cancellation Option */}
                        {['Pending', 'Confirmed'].includes(order.orderStatus) && (
                          <button 
                            onClick={() => setCancellationModal({ open: true, orderId: order.id, reason: '' })}
                            className="mt-3 w-full py-1.5 border border-rose-300 text-rose-600 hover:bg-rose-50 font-bold text-xs rounded-lg transition"
                          >
                            Cancel Order
                          </button>
                        )}
                      </div>

                    </div>

                    {/* Rejection / Cancellation Reason Banner */}
                    {order.cancellationReason && (
                      <div className="bg-rose-50 border border-rose-200 p-3 rounded-xl text-xs text-rose-800">
                        <strong>Reason for Cancellation / Rejection:</strong> {order.cancellationReason}
                      </div>
                    )}

                  </div>
                ))}
              </div>
            )}
          </div>
        )}

        {/* ==================== CUSTOMER PROFILE ==================== */}
        {activeTab === 'my_profile' && currentUser && (
          <div className="max-w-xl mx-auto bg-white rounded-2xl border border-slate-200 p-8 shadow-sm space-y-6">
            <div>
              <h2 className="text-2xl font-bold text-slate-900">Customer Profile Settings</h2>
              <p className="text-xs text-slate-500">Update your contact information for refilling deliveries.</p>
            </div>

            <div className="space-y-4 text-sm">
              <div>
                <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Full Name</label>
                <input type="text" defaultValue={currentUser.name} className="w-full px-3.5 py-2.5 border rounded-xl bg-slate-50" readOnly />
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Email Address</label>
                <input type="email" defaultValue={currentUser.email} className="w-full px-3.5 py-2.5 border rounded-xl bg-slate-50" readOnly />
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Contact Phone Number</label>
                <input type="text" defaultValue={currentUser.phone} className="w-full px-3.5 py-2.5 border rounded-xl" />
              </div>
              <div>
                <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Default Delivery Address</label>
                <textarea rows={2} defaultValue={currentUser.address} className="w-full px-3.5 py-2.5 border rounded-xl" />
              </div>
              <button className="w-full py-2.5 bg-blue-600 text-white font-bold rounded-xl shadow">Save Updated Profile</button>
            </div>
          </div>
        )}

        {/* ==================== ADMIN DASHBOARD ==================== */}
        {activeTab === 'admin_dashboard' && currentUser?.role === 'admin' && (
          <div className="space-y-8">
            <div>
              <h2 className="text-3xl font-black text-slate-900">Administrator Console</h2>
              <p className="text-slate-500 text-sm">Overview of operations, delivery schedules, and station sales.</p>
            </div>

            {/* METRICS CARDS */}
            <div className="grid grid-cols-2 sm:grid-cols-4 lg:grid-cols-8 gap-3">
              {[
                { label: 'Total Orders', count: adminStats.total, color: 'bg-slate-100 text-slate-800' },
                { label: 'Pending', count: adminStats.pending, color: 'bg-amber-100 text-amber-800' },
                { label: 'Confirmed', count: adminStats.confirmed, color: 'bg-blue-100 text-blue-800' },
                { label: 'Preparing', count: adminStats.preparing, color: 'bg-purple-100 text-purple-800' },
                { label: 'Out for Delivery', count: adminStats.outForDelivery, color: 'bg-cyan-100 text-cyan-800' },
                { label: 'Delivered', count: adminStats.delivered, color: 'bg-emerald-100 text-emerald-800' },
                { label: 'Cancelled', count: adminStats.cancelled, color: 'bg-rose-100 text-rose-800' },
                { label: 'Completed Sales', count: `₱${adminStats.totalSales}`, color: 'bg-emerald-600 text-white col-span-2 sm:col-span-1' }
              ].map((m, idx) => (
                <div key={idx} className={`p-4 rounded-2xl border border-slate-200/80 shadow-sm ${m.color}`}>
                  <p className="text-[10px] font-bold uppercase tracking-wider opacity-80">{m.label}</p>
                  <p className="text-2xl font-black mt-1">{m.count}</p>
                </div>
              ))}
            </div>

            {/* QUICK ORDER STATUS MANAGEMENT TABLE */}
            <div className="bg-white rounded-2xl border border-slate-200 shadow-sm p-6 space-y-4">
              <div className="flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4">
                <h3 className="text-xl font-bold text-slate-900">Recent Customer Orders</h3>
                <button onClick={() => setActiveTab('admin_orders')} className="text-sm font-bold text-blue-600 hover:underline">
                  Full Order Manager &rarr;
                </button>
              </div>

              <div className="overflow-x-auto">
                <table className="w-full text-left text-xs">
                  <thead className="bg-slate-50 text-slate-500 uppercase border-b border-slate-200">
                    <tr>
                      <th className="p-3">Order ID</th>
                      <th className="p-3">Customer</th>
                      <th className="p-3">Amount</th>
                      <th className="p-3">Payment Method</th>
                      <th className="p-3">Status</th>
                      <th className="p-3">Action</th>
                    </tr>
                  </thead>
                  <tbody className="divide-y divide-slate-100">
                    {orders.slice(0, 5).map(o => (
                      <tr key={o.id}>
                        <td className="p-3 font-bold text-slate-900">{o.id}</td>
                        <td className="p-3 font-medium text-slate-700">{o.customerName}</td>
                        <td className="p-3 font-bold text-blue-600">₱{o.totalAmount}</td>
                        <td className="p-3">{o.paymentMethod} ({o.paymentStatus})</td>
                        <td className="p-3">
                          <span className="px-2 py-0.5 rounded font-bold text-[10px] bg-slate-100 text-slate-800">
                            {o.orderStatus}
                          </span>
                        </td>
                        <td className="p-3">
                          <button onClick={() => setActiveTab('admin_orders')} className="text-blue-600 font-bold hover:underline">
                            Manage
                          </button>
                        </td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {/* ==================== ADMIN ORDERS MANAGEMENT ==================== */}
        {activeTab === 'admin_orders' && currentUser?.role === 'admin' && (
          <div className="space-y-6">
            <div>
              <h2 className="text-3xl font-black text-slate-900">Order Management</h2>
              <p className="text-slate-500 text-sm">Review, confirm schedules, update processing statuses, and verify payments.</p>
            </div>

            {/* SEARCH AND FILTER BAR */}
            <div className="bg-white p-4 rounded-2xl border border-slate-200 flex flex-col sm:flex-row gap-4 justify-between items-center">
              <div className="relative w-full sm:w-80">
                <Search className="w-4 h-4 text-slate-400 absolute left-3 top-3" />
                <input 
                  type="text"
                  placeholder="Search by Order # or Customer..."
                  value={adminSearchQuery}
                  onChange={e => setAdminSearchQuery(e.target.value)}
                  className="w-full pl-9 pr-3 py-2 border rounded-xl text-xs outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              <div className="flex items-center gap-2 w-full sm:w-auto">
                <Filter className="w-4 h-4 text-slate-500" />
                <select 
                  value={adminStatusFilter} 
                  onChange={e => setAdminStatusFilter(e.target.value)}
                  className="px-3 py-2 border rounded-xl text-xs bg-white outline-none font-medium"
                >
                  <option value="ALL">All Statuses</option>
                  <option value="Pending">Pending</option>
                  <option value="Confirmed">Confirmed</option>
                  <option value="Preparing">Preparing</option>
                  <option value="Out for Delivery">Out for Delivery</option>
                  <option value="Delivered">Delivered</option>
                  <option value="Cancelled">Cancelled</option>
                </select>
              </div>
            </div>

            {/* ORDER CONTROL LIST */}
            <div className="space-y-4">
              {filteredOrders.length === 0 ? (
                <div className="bg-white p-12 rounded-2xl text-center text-slate-400 font-medium">
                  No customer orders match the search criteria.
                </div>
              ) : (
                filteredOrders.map(order => (
                  <div key={order.id} className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm space-y-4">
                    
                    <div className="flex flex-wrap justify-between items-start gap-4 border-b border-slate-100 pb-3">
                      <div>
                        <div className="flex items-center gap-2">
                          <span className="font-extrabold text-lg text-slate-900">{order.id}</span>
                          <span className="text-xs text-slate-400">• {order.orderDate}</span>
                        </div>
                        <p className="text-xs font-bold text-slate-700 mt-1">Customer: {order.customerName} ({order.contactNumber})</p>
                        <p className="text-xs text-slate-500">Address: {order.deliveryAddress}</p>
                      </div>

                      {/* WORKFLOW STATUS UPDATER BUTTONS */}
                      <div className="flex flex-col items-end gap-2">
                        <div className="flex items-center gap-1.5">
                          <span className="text-xs font-bold text-slate-500">Update Workflow:</span>
                          <select 
                            value={order.orderStatus}
                            onChange={(e) => handleUpdateOrderStatus(order.id, e.target.value)}
                            className="px-3 py-1.5 border rounded-lg text-xs font-bold bg-slate-50 outline-none cursor-pointer"
                          >
                            <option value="Pending">Pending</option>
                            <option value="Confirmed">Confirmed</option>
                            <option value="Preparing">Preparing</option>
                            <option value="Out for Delivery">Out for Delivery</option>
                            <option value="Delivered">Delivered</option>
                            <option value="Cancelled">Cancelled</option>
                          </select>
                        </div>

                        {order.orderStatus !== 'Cancelled' && (
                          <button 
                            onClick={() => setRejectionModal({ open: true, orderId: order.id, reason: '' })}
                            className="text-xs text-rose-600 font-bold hover:underline"
                          >
                            Reject / Cancel Order
                          </button>
                        )}
                      </div>
                    </div>

                    {/* ITEMS & PAYMENT VERIFICATION CONTROL */}
                    <div className="grid grid-cols-1 md:grid-cols-3 gap-4 text-xs">
                      
                      {/* Products */}
                      <div className="bg-slate-50 p-3 rounded-xl border border-slate-100">
                        <p className="font-bold text-slate-700 uppercase text-[10px] mb-1">Items Summary</p>
                        <ul className="space-y-1">
                          {order.items.map((it, idx) => (
                            <li key={idx} className="flex justify-between">
                              <span>{it.quantity}x {it.name}</span>
                              <span className="font-bold">₱{it.unitPrice * it.quantity}</span>
                            </li>
                          ))}
                        </ul>
                        <div className="mt-2 pt-2 border-t border-slate-200 flex justify-between font-black text-sm">
                          <span>Total Amount:</span>
                          <span className="text-blue-600">₱{order.totalAmount}</span>
                        </div>
                      </div>

                      {/* Delivery Schedule Confirmation */}
                      <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 space-y-1">
                        <p className="font-bold text-slate-700 uppercase text-[10px]">Schedule Confirmation</p>
                        <p>Requested: <span className="font-semibold">{order.requestedSchedule.date} ({order.requestedSchedule.time})</span></p>
                        <p>Confirmed Slot: <span className="font-bold text-emerald-700">{order.confirmedSchedule || 'Not set'}</span></p>
                        {order.deliveryInstructions && (
                          <p className="text-slate-500 italic text-[11px] mt-1">Instructions: "{order.deliveryInstructions}"</p>
                        )}
                      </div>

                      {/* Payment Status Switch */}
                      <div className="bg-slate-50 p-3 rounded-xl border border-slate-100 flex flex-col justify-between">
                        <div>
                          <p className="font-bold text-slate-700 uppercase text-[10px]">Payment Verification</p>
                          <p className="font-semibold text-slate-900">{order.paymentMethod}</p>
                          <p className="text-[11px] text-slate-500">Status: <strong className={order.paymentStatus === 'Verified' ? 'text-emerald-700' : 'text-amber-700'}>{order.paymentStatus}</strong></p>
                        </div>

                        <div className="flex gap-2 mt-2">
                          <button 
                            onClick={() => handleUpdatePaymentStatus(order.id, 'Verified')}
                            className="flex-1 py-1 bg-emerald-600 text-white font-bold rounded text-[11px] hover:bg-emerald-700 transition"
                          >
                            Mark Verified
                          </button>
                          <button 
                            onClick={() => handleUpdatePaymentStatus(order.id, 'Pending')}
                            className="flex-1 py-1 border border-slate-300 text-slate-700 font-bold rounded text-[11px] hover:bg-slate-100 transition"
                          >
                            Mark Unverified
                          </button>
                        </div>
                      </div>

                    </div>

                    {order.cancellationReason && (
                      <div className="bg-rose-50 border border-rose-200 p-2.5 rounded-xl text-xs text-rose-800">
                        <strong>Cancellation/Rejection Reason Recorded:</strong> {order.cancellationReason}
                      </div>
                    )}

                  </div>
                ))
              )}
            </div>
          </div>
        )}

        {/* ==================== ADMIN PRODUCT MANAGEMENT ==================== */}
        {activeTab === 'admin_products' && currentUser?.role === 'admin' && (
          <div className="space-y-8">
            <div className="flex justify-between items-center">
              <div>
                <h2 className="text-3xl font-black text-slate-900">Product Catalog & Pricing Manager</h2>
                <p className="text-slate-500 text-sm">Add, update prices, activate, or deactivate products directly in real-time.</p>
              </div>
            </div>

            {/* ADD / EDIT PRODUCT FORM */}
            <div className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm">
              <h3 className="font-bold text-slate-900 text-lg mb-4">
                {editingProduct ? 'Edit Product Details' : 'Add New Product to Catalog'}
              </h3>
              
              <form onSubmit={handleSaveProduct} className="grid grid-cols-1 md:grid-cols-3 gap-4">
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Product Name</label>
                  <input 
                    type="text" 
                    required 
                    placeholder="e.g. Slim 15L Container Refill"
                    value={editingProduct ? editingProduct.name : newProductForm.name}
                    onChange={e => editingProduct ? setEditingProduct({ ...editingProduct, name: e.target.value }) : setNewProductForm({ ...newProductForm, name: e.target.value })}
                    className="w-full px-3 py-2 border rounded-xl text-xs outline-none" 
                  />
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Category</label>
                  <select 
                    value={editingProduct ? editingProduct.category : newProductForm.category}
                    onChange={e => editingProduct ? setEditingProduct({ ...editingProduct, category: e.target.value }) : setNewProductForm({ ...newProductForm, category: e.target.value })}
                    className="w-full px-3 py-2 border rounded-xl text-xs bg-white outline-none"
                  >
                    <option value="refill">Water Refills</option>
                    <option value="empty">Empty Gallons Only</option>
                    <option value="new_with_water">New Gallon with Water</option>
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Price (Philippine Pesos ₱)</label>
                  <input 
                    type="number" 
                    required 
                    value={editingProduct ? editingProduct.price : newProductForm.price}
                    onChange={e => editingProduct ? setEditingProduct({ ...editingProduct, price: Number(e.target.value) }) : setNewProductForm({ ...newProductForm, price: e.target.value })}
                    className="w-full px-3 py-2 border rounded-xl text-xs outline-none" 
                  />
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Capacity</label>
                  <input 
                    type="text" 
                    required 
                    placeholder="20 Liters / 10 Liters"
                    value={editingProduct ? editingProduct.capacity : newProductForm.capacity}
                    onChange={e => editingProduct ? setEditingProduct({ ...editingProduct, capacity: e.target.value }) : setNewProductForm({ ...newProductForm, capacity: e.target.value })}
                    className="w-full px-3 py-2 border rounded-xl text-xs outline-none" 
                  />
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Icon Style</label>
                  <select 
                    value={editingProduct ? editingProduct.image : newProductForm.image}
                    onChange={e => editingProduct ? setEditingProduct({ ...editingProduct, image: e.target.value }) : setNewProductForm({ ...newProductForm, image: e.target.value })}
                    className="w-full px-3 py-2 border rounded-xl text-xs bg-white outline-none"
                  >
                    <option value="rect-faucet">Rectangular Container with Faucet</option>
                    <option value="round">Standard Round Gallon</option>
                    <option value="rect-faucet-half">Half-Size Compact Container</option>
                  </select>
                </div>

                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Description</label>
                  <input 
                    type="text" 
                    required 
                    placeholder="Short summary of container"
                    value={editingProduct ? editingProduct.desc : newProductForm.desc}
                    onChange={e => editingProduct ? setEditingProduct({ ...editingProduct, desc: e.target.value }) : setNewProductForm({ ...newProductForm, desc: e.target.value })}
                    className="w-full px-3 py-2 border rounded-xl text-xs outline-none" 
                  />
                </div>

                <div className="md:col-span-3 flex justify-end gap-2 pt-2">
                  {editingProduct && (
                    <button type="button" onClick={() => setEditingProduct(null)} className="px-4 py-2 border rounded-xl text-xs font-bold text-slate-600">
                      Cancel Editing
                    </button>
                  )}
                  <button type="submit" className="px-6 py-2 bg-blue-600 text-white font-bold rounded-xl text-xs shadow hover:bg-blue-700">
                    {editingProduct ? 'Update Product' : 'Add Product'}
                  </button>
                </div>
              </form>
            </div>

            {/* PRODUCT CATALOG TABLE */}
            <div className="bg-white rounded-2xl border border-slate-200 overflow-hidden shadow-sm">
              <table className="w-full text-left text-xs">
                <thead className="bg-slate-50 text-slate-500 uppercase border-b border-slate-200">
                  <tr>
                    <th className="p-3">Product Name</th>
                    <th className="p-3">Category</th>
                    <th className="p-3">Capacity</th>
                    <th className="p-3">Price</th>
                    <th className="p-3">Status</th>
                    <th className="p-3 text-right">Actions</th>
                  </tr>
                </thead>
                <tbody className="divide-y divide-slate-100">
                  {products.map(p => (
                    <tr key={p.id}>
                      <td className="p-3 font-bold text-slate-900">{p.name}</td>
                      <td className="p-3 font-medium capitalize text-slate-600">{p.category.replace('_', ' ')}</td>
                      <td className="p-3 text-slate-500">{p.capacity}</td>
                      <td className="p-3 font-black text-blue-600">₱{p.price}</td>
                      <td className="p-3">
                        <span className={`px-2 py-0.5 rounded font-bold text-[10px] ${p.active ? 'bg-emerald-100 text-emerald-800' : 'bg-slate-100 text-slate-500'}`}>
                          {p.active ? 'Active' : 'Inactive'}
                        </span>
                      </td>
                      <td className="p-3 text-right space-x-2">
                        <button onClick={() => setEditingProduct(p)} className="text-blue-600 font-bold hover:underline">
                          Edit
                        </button>
                        <button onClick={() => handleToggleProductActive(p.id)} className="text-slate-500 font-bold hover:underline">
                          {p.active ? 'Deactivate' : 'Activate'}
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* ==================== ADMIN PAYMENT SETTINGS ==================== */}
        {activeTab === 'admin_payments' && currentUser?.role === 'admin' && (
          <div className="max-w-2xl mx-auto space-y-6">
            <div>
              <h2 className="text-3xl font-black text-slate-900">Payment Instructions Configurator</h2>
              <p className="text-slate-500 text-sm">Configure account numbers and instructions shown to customers during checkout.</p>
            </div>

            {Object.keys(paymentConfig).map(key => (
              <div key={key} className="bg-white rounded-2xl border border-slate-200 p-6 shadow-sm space-y-3">
                <h3 className="font-bold text-slate-900 uppercase text-sm border-b border-slate-100 pb-2">
                  {paymentConfig[key].title} Configuration
                </h3>
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Account Name</label>
                  <input 
                    type="text" 
                    value={paymentConfig[key].accountName}
                    onChange={e => setPaymentConfig({
                      ...paymentConfig,
                      [key]: { ...paymentConfig[key], accountName: e.target.value }
                    })}
                    className="w-full px-3 py-2 border rounded-xl text-xs outline-none"
                  />
                </div>
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Account / Mobile Number</label>
                  <input 
                    type="text" 
                    value={paymentConfig[key].accountNumber}
                    onChange={e => setPaymentConfig({
                      ...paymentConfig,
                      [key]: { ...paymentConfig[key], accountNumber: e.target.value }
                    })}
                    className="w-full px-3 py-2 border rounded-xl text-xs outline-none"
                  />
                </div>
                <div>
                  <label className="block text-xs font-bold text-slate-700 uppercase mb-1">Customer Payment Instructions</label>
                  <textarea 
                    rows={2}
                    value={paymentConfig[key].instructions}
                    onChange={e => setPaymentConfig({
                      ...paymentConfig,
                      [key]: { ...paymentConfig[key], instructions: e.target.value }
                    })}
                    className="w-full px-3 py-2 border rounded-xl text-xs outline-none"
                  />
                </div>
              </div>
            ))}
          </div>
        )}

        {/* ==================== DB SETUP & SUPABASE TECHNICAL GUIDE ==================== */}
        {activeTab === 'setup_guide' && (
          <div className="max-w-3xl mx-auto bg-white rounded-2xl border border-slate-200 p-8 shadow-sm space-y-6">
            <div>
              <h2 className="text-2xl font-black text-slate-900">Backend & Security Deployment Guide</h2>
              <p className="text-slate-500 text-xs mt-1">Instructions for configuring Supabase Row Level Security (RLS) & First Administrator account.</p>
            </div>

            <div className="space-y-4 text-xs text-slate-700">
              <div className="bg-slate-900 text-slate-100 p-4 rounded-xl overflow-x-auto font-mono text-[11px] leading-relaxed">
                <p className="text-emerald-400 font-bold mb-2">-- Supabase PostgreSQL Database Schema & RLS Policies</p>
                <pre>{`
CREATE TABLE public.products (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  category TEXT NOT NULL,
  name TEXT NOT NULL,
  capacity TEXT NOT NULL,
  price NUMERIC NOT NULL,
  active BOOLEAN DEFAULT TRUE
);

CREATE TABLE public.orders (
  id TEXT PRIMARY KEY,
  customer_id UUID REFERENCES auth.users(id),
  customer_name TEXT NOT NULL,
  contact_number TEXT NOT NULL,
  delivery_address TEXT NOT NULL,
  items JSONB NOT NULL,
  total_amount NUMERIC NOT NULL,
  payment_method TEXT NOT NULL,
  payment_status TEXT DEFAULT 'Pending',
  order_status TEXT DEFAULT 'Pending',
  requested_schedule JSONB NOT NULL,
  confirmed_schedule TEXT,
  cancellation_reason TEXT,
  created_at TIMESTAMPTZ DEFAULT now()
);

-- Enable RLS
ALTER TABLE public.orders ENABLE ROW LEVEL SECURITY;

-- Customers can view only their own orders
CREATE POLICY "Customer Orders Policy" ON public.orders
  FOR SELECT USING (auth.uid() = customer_id);

-- Administrators full access
CREATE POLICY "Admin Full Access" ON public.orders
  FOR ALL USING (
    EXISTS (
      SELECT 1 FROM public.user_roles 
      WHERE user_id = auth.uid() AND role = 'admin'
    )
  );
                `}</pre>
              </div>

              <div className="bg-blue-50 p-4 rounded-xl border border-blue-200 text-blue-900 space-y-1">
                <p className="font-bold">🔒 Secure First Administrator Creation:</p>
                <p>1. Register a user email via Supabase Auth standard signup.</p>
                <p>2. Insert record into `public.user_roles` with `role = 'admin'` directly via Supabase SQL Editor.</p>
                <p>3. Public customer registration form never exposes or accepts administrator privileges.</p>
              </div>
            </div>
          </div>
        )}

      </main>

      {/* FOOTER */}
      <footer className="bg-slate-900 text-slate-400 text-xs py-8 border-t border-slate-800 mt-auto">
        <div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 flex flex-col sm:flex-row justify-between items-center gap-4">
          <div>
            <p className="font-bold text-slate-200">JP WATER REFILLING STATION</p>
            <p className="mt-0.5 text-slate-500">Cabanatuan City, Nueva Ecija • Contact: 0949-360-8711 / 0908-298-0925</p>
          </div>
          <p className="text-slate-600">© 2026 JP Water Refilling. All rights reserved.</p>
        </div>
      </footer>

      {/* CANCELLATION MODAL */}
      {cancellationModal.open && (
        <div className="fixed inset-0 bg-slate-950/60 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl max-w-md w-full p-6 space-y-4 shadow-2xl">
            <h3 className="text-lg font-bold text-slate-900">Cancel Order {cancellationModal.orderId}</h3>
            <p className="text-xs text-slate-500">Please provide a reason for cancelling this order:</p>
            <textarea 
              rows={3} 
              value={cancellationModal.reason} 
              onChange={e => setCancellationModal({ ...cancellationModal, reason: e.target.value })}
              placeholder="e.g. Schedule conflict / Placed order by mistake"
              className="w-full px-3 py-2 border rounded-xl text-xs outline-none focus:ring-2 focus:ring-rose-500" 
            />
            <div className="flex gap-2 justify-end">
              <button onClick={() => setCancellationModal({ open: false, orderId: null, reason: '' })} className="px-4 py-2 border rounded-xl text-xs font-bold text-slate-600">
                Back
              </button>
              <button onClick={handleCancelOrderSubmit} className="px-4 py-2 bg-rose-600 text-white rounded-xl text-xs font-bold hover:bg-rose-700">
                Confirm Cancellation
              </button>
            </div>
          </div>
        </div>
      )}

      {/* REJECTION MODAL */}
      {rejectionModal.open && (
        <div className="fixed inset-0 bg-slate-950/60 backdrop-blur-sm flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-2xl max-w-md w-full p-6 space-y-4 shadow-2xl">
            <h3 className="text-lg font-bold text-slate-900">Reject / Cancel Order {rejectionModal.orderId}</h3>
            <p className="text-xs text-slate-500">Record a reason that will be visible to the customer:</p>
            <textarea 
              rows={3} 
              value={rejectionModal.reason} 
              onChange={e => setRejectionModal({ ...rejectionModal, reason: e.target.value })}
              placeholder="e.g. Outside delivery area slot today / Out of stock container"
              className="w-full px-3 py-2 border rounded-xl text-xs outline-none focus:ring-2 focus:ring-rose-500" 
            />
            <div className="flex gap-2 justify-end">
              <button onClick={() => setRejectionModal({ open: false, orderId: null, reason: '' })} className="px-4 py-2 border rounded-xl text-xs font-bold text-slate-600">
                Cancel
              </button>
              <button onClick={handleAdminRejectOrder} className="px-4 py-2 bg-rose-600 text-white rounded-xl text-xs font-bold hover:bg-rose-700">
                Reject Order & Record Reason
              </button>
            </div>
          </div>
        </div>
      )}

    </div>
  );
}

window.__JPWATER_APP__ = App;
