// ═══════════════════════════════════════════════════════════════
// ModuSystems Order Portal — Firebase-wired version
// Requires: firebase-app-compat, firebase-auth-compat,
//           firebase-firestore-compat, firebase-storage-compat
//           loaded in orders.html BEFORE this file.
//           Globals available: auth, db, storage, firebase
// ═══════════════════════════════════════════════════════════════

const { useState, useEffect, useRef } = React;

const ACCENT = "#f59e0b";
const BG_DARK = "#0a0f1a";
const BG_CARD = "#111827";
const BG_INPUT = "#1a2234";
const BORDER = "#1f2937";
const TEXT_PRIMARY = "#e5e7eb";
const TEXT_SECONDARY = "#9ca3af";
const TEXT_MUTED = "#6b7280";
const GREEN = "#10b981";
const RED = "#ef4444";
const BLUE = "#3b82f6";

// Admin emails — add yours here
const ADMIN_EMAILS = ["g2motion1@gmail.com"];

// ── EmailJS Config ──
// Sign up free at emailjs.com, then fill these in:
const EMAILJS_SERVICE_ID  = "service_52bhpz1";
const EMAILJS_PUBLIC_KEY  = "oTVvNY94K9OBvpZa9";
const EMAILJS_TEMPLATE_APPROVED = "template_5qkq51n";
const EMAILJS_TEMPLATE_REJECTED = "template_5qkq51n"; // reuse approved template for now
const EMAILJS_TEMPLATE_SUBMITTED = "template_r29dlzb";
const ADMIN_NOTIFY_EMAIL = "g2motion1@gmail.com";

async function sendEmail(templateId, params) {
  try {
    if (!window.emailjs || EMAILJS_SERVICE_ID === "YOUR_SERVICE_ID") {
      console.warn("EmailJS not configured — skipping email");
      return;
    }
    await window.emailjs.send(EMAILJS_SERVICE_ID, templateId, params, EMAILJS_PUBLIC_KEY);
    console.log("Email sent:", templateId);
  } catch (err) {
    console.error("Email send failed:", err);
    // Don't block the UI — email failure is non-critical
  }
}

const STATUS_COLORS = {
  pending:      { bg: "#f59e0b20", text: "#f59e0b", label: "Awaiting PO" },
  po_uploaded:  { bg: "#3b82f620", text: "#3b82f6", label: "PO Submitted" },
  under_review: { bg: "#8b5cf620", text: "#8b5cf6", label: "Under Review" },
  approved:     { bg: "#10b98120", text: "#10b981", label: "Approved" },
  processing:   { bg: "#06b6d420", text: "#06b6d4", label: "Processing" },
  shipped:      { bg: "#3b82f620", text: "#3b82f6", label: "Shipped" },
  delivered:    { bg: "#10b98120", text: "#10b981", label: "Delivered" },
  rejected:     { bg: "#ef444420", text: "#ef4444", label: "Rejected" },
  paid:         { bg: "#10b98120", text: "#10b981", label: "Paid" },
};

function StatusBadge({ status }) {
  const s = STATUS_COLORS[status] || STATUS_COLORS.pending;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 6,
      padding: "4px 12px", borderRadius: 20,
      background: s.bg, color: s.text,
      fontSize: 12, fontWeight: 700, letterSpacing: "0.03em",
      textTransform: "uppercase", whiteSpace: "nowrap"
    }}>
      <span style={{ width: 6, height: 6, borderRadius: "50%", background: s.text }} />
      {s.label}
    </span>
  );
}

// ── Auth Screen ──
function AuthScreen({ onLogin }) {
  const [mode, setMode] = useState("login");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [company, setCompany] = useState("");
  const [phone, setPhone] = useState("");
  const [error, setError] = useState("");
  const [loading, setLoading] = useState(false);

  const handleSubmit = async () => {
    setError("");
    if (!email || !password) { setError("Email and password required"); return; }
    if (mode === "register" && !company) { setError("Company name required"); return; }
    if (!email.includes("@") || !email.includes(".")) { setError("Valid email required"); return; }
    if (password.length < 8) { setError("Password must be at least 8 characters"); return; }
    setLoading(true);
    try {
      if (mode === "register") {
        const userCred = await auth.createUserWithEmailAndPassword(email, password);
        await db.collection("customers").doc(userCred.user.uid).set({
          email,
          company,
          phone: phone || "",
          createdAt: firebase.firestore.FieldValue.serverTimestamp()
        });
        onLogin({ email, company, uid: userCred.user.uid });
      } else {
        const userCred = await auth.signInWithEmailAndPassword(email, password);
        let custData = {};
        const custDoc = await db.collection("customers").doc(userCred.user.uid).get();
        if (custDoc.exists) {
          custData = custDoc.data();
        } else {
          const userDoc = await db.collection("users").doc(userCred.user.uid).get();
          if (userDoc.exists) custData = { company: userDoc.data().name, ...userDoc.data() };
        }
        onLogin({
          email,
          company: custData.company || custData.name || email.split("@")[0],
          uid: userCred.user.uid
        });
      }
    } catch (err) {
      const msgs = {
        "auth/user-not-found": "No account found with this email.",
        "auth/wrong-password": "Incorrect password.",
        "auth/email-already-in-use": "An account with this email already exists.",
        "auth/too-many-requests": "Too many attempts. Please try again later.",
        "auth/invalid-email": "Invalid email address.",
      };
      setError(msgs[err.code] || err.message);
    } finally {
      setLoading(false);
    }
  };

  const inputStyle = {
    width: "100%", padding: "14px 16px", borderRadius: 8,
    border: `1px solid ${BORDER}`, background: BG_INPUT, color: TEXT_PRIMARY,
    fontSize: 15, fontFamily: "'DM Sans', sans-serif", outline: "none",
    boxSizing: "border-box", transition: "border-color 0.2s",
  };

  return (
    <div style={{
      minHeight: "100vh", background: BG_DARK, display: "flex",
      alignItems: "center", justifyContent: "center", padding: 20,
      fontFamily: "'DM Sans', sans-serif"
    }}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet" />
      <div style={{
        background: BG_CARD, borderRadius: 16, border: `1px solid ${BORDER}`,
        padding: "48px 40px", maxWidth: 420, width: "100%",
        boxShadow: "0 25px 50px rgba(0,0,0,0.5)"
      }}>
        {/* Logo */}
        <div style={{ textAlign: "center", marginBottom: 32 }}>
          <div style={{ fontSize: 36, fontWeight: 800, color: TEXT_PRIMARY, letterSpacing: "-0.03em" }}>
            <span style={{ color: ACCENT }}>MODU</span>SYSTEMS
          </div>
          <div style={{ fontSize: 13, color: TEXT_MUTED, marginTop: 4, letterSpacing: "0.05em", textTransform: "uppercase" }}>
            Order Portal
          </div>
        </div>

        {/* Tabs */}
        <div style={{ display: "flex", gap: 0, marginBottom: 28, borderRadius: 8, overflow: "hidden", border: `1px solid ${BORDER}` }}>
          {["login", "register"].map(m => (
            <button key={m} onClick={() => { setMode(m); setError(""); }}
              style={{
                flex: 1, padding: "10px 0", border: "none", cursor: "pointer",
                background: mode === m ? ACCENT : "transparent",
                color: mode === m ? "#0a0f1a" : TEXT_MUTED,
                fontWeight: 700, fontSize: 13, fontFamily: "inherit",
                textTransform: "uppercase", letterSpacing: "0.05em",
                transition: "all 0.2s"
              }}>
              {m === "login" ? "Sign In" : "Register"}
            </button>
          ))}
        </div>

        {/* Form */}
        <div style={{ display: "flex", flexDirection: "column", gap: 14 }}>
          <input type="email" placeholder="Email address" value={email}
            onChange={e => setEmail(e.target.value)} style={inputStyle}
            onFocus={e => e.target.style.borderColor = ACCENT}
            onBlur={e => e.target.style.borderColor = BORDER} />
          <input type="password" placeholder="Password" value={password}
            onChange={e => setPassword(e.target.value)} style={inputStyle}
            onFocus={e => e.target.style.borderColor = ACCENT}
            onBlur={e => e.target.style.borderColor = BORDER}
            onKeyDown={e => e.key === "Enter" && handleSubmit()} />
          {mode === "register" && (
            <>
              <input type="text" placeholder="Company name *" value={company}
                onChange={e => setCompany(e.target.value)} style={inputStyle}
                onFocus={e => e.target.style.borderColor = ACCENT}
                onBlur={e => e.target.style.borderColor = BORDER} />
              <input type="tel" placeholder="Phone (optional)" value={phone}
                onChange={e => setPhone(e.target.value)} style={inputStyle}
                onFocus={e => e.target.style.borderColor = ACCENT}
                onBlur={e => e.target.style.borderColor = BORDER} />
            </>
          )}
        </div>

        {error && (
          <div style={{ marginTop: 12, padding: "10px 14px", borderRadius: 8, background: "#ef444420", color: RED, fontSize: 13, fontWeight: 500 }}>
            ⚠ {error}
          </div>
        )}

        <button onClick={handleSubmit} disabled={loading}
          style={{
            width: "100%", padding: "14px 0", marginTop: 20, border: "none",
            borderRadius: 8, background: loading ? TEXT_MUTED : ACCENT,
            color: "#0a0f1a", fontSize: 15, fontWeight: 700, cursor: loading ? "wait" : "pointer",
            fontFamily: "inherit", letterSpacing: "0.02em", transition: "all 0.2s"
          }}>
          {loading ? "Processing..." : mode === "login" ? "Sign In" : "Create Account"}
        </button>

        <div style={{ textAlign: "center", marginTop: 20, fontSize: 12, color: TEXT_MUTED }}>
          By continuing, you agree to our terms of service.
          <br />Purchase orders reviewed within 24 business hours.
        </div>
      </div>
    </div>
  );
}

// ── PO Upload Modal ──
function POUploadModal({ quote, user, onClose, onUpload }) {
  const [file, setFile] = useState(null);
  const [dragOver, setDragOver] = useState(false);
  const [notes, setNotes] = useState("");
  const [uploading, setUploading] = useState(false);
  const [uploadProgress, setUploadProgress] = useState(0);
  const [error, setError] = useState("");
  const [success, setSuccess] = useState(false);
  const fileRef = useRef(null);

  const validateFile = (f) => {
    if (!f) return "No file selected";
    if (f.type !== "application/pdf") return "Only PDF files accepted";
    if (f.size > 10 * 1024 * 1024) return "File must be under 10MB";
    return null;
  };

  const handleFile = (f) => {
    const err = validateFile(f);
    if (err) { setError(err); setFile(null); return; }
    setError("");
    setFile(f);
  };

  const handleDrop = (e) => {
    e.preventDefault();
    setDragOver(false);
    if (e.dataTransfer.files.length > 0) handleFile(e.dataTransfer.files[0]);
  };

  const handleUpload = async () => {
    if (!file) { setError("Please select a PDF file"); return; }
    setUploading(true);
    setError("");
    try {
      // Verify user is authenticated
      const currentUser = auth.currentUser;
      if (!currentUser) { setError("Not logged in. Please refresh and sign in again."); setUploading(false); return; }

      // Use firestoreId as the folder name, fall back to quoteNumber or id
      const quoteFolder = quote.firestoreId || quote.id || quote.quoteNumber || "unknown";
      const storagePath = `po-uploads/${quoteFolder}/${file.name}`;
      const storageRef = storage.ref(storagePath);
      const uploadTask = storageRef.put(file, { contentType: "application/pdf" });

      await new Promise((resolve, reject) => {
        uploadTask.on(
          "state_changed",
          (snap) => setUploadProgress(Math.round((snap.bytesTransferred / snap.totalBytes) * 100)),
          reject,
          resolve
        );
      });

      // Create order document in Firestore
      await db.collection("orders").add({
        quoteId: quote.id,
        customerEmail: user.email,
        customer: user.company,
        total: quote.total,
        status: "po_uploaded",
        poFileName: file.name,
        poStoragePath: storagePath,
        notes: notes || "",
        items: quote.items.map(i => i.name).join(", "),
        createdAt: firebase.firestore.FieldValue.serverTimestamp()
      });

      // Mark quote as po_uploaded - use firestoreId directly if available
      if (quote.firestoreId) {
        await db.collection("quotes").doc(quote.firestoreId).update({ status: "po_uploaded" });
      } else {
        const snap = await db.collection("quotes")
          .where("id", "==", quote.id).limit(1).get();
        if (!snap.empty) await snap.docs[0].ref.update({ status: "po_uploaded" });
      }

      // Notify admin of new PO submission
      await sendEmail(EMAILJS_TEMPLATE_SUBMITTED, {
        to_email: ADMIN_NOTIFY_EMAIL,
        to_name: "ModuSystems Team",
        customer_name: user.company || user.email,
        customer_email: user.email,
        quote_id: quote.id || quote.quoteNumber,
        order_total: `$${(quote.total || quote.totalPrice || 0).toLocaleString()}`,
        po_filename: file.name,
        notes: notes || "None",
        portal_url: "https://ai.modusystems.com/orders",
        reply_to: user.email,
      });

      setUploading(false);
      setSuccess(true);
      setTimeout(() => onUpload(quote.id, file.name), 1500);
    } catch (err) {
      setUploading(false);
      setError("Upload failed: " + err.message);
    }
  };

  if (success) {
    return (
      <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.7)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 9999 }}>
        <div style={{ background: BG_CARD, borderRadius: 16, border: `1px solid ${BORDER}`, padding: "48px 40px", maxWidth: 440, width: "90%", textAlign: "center" }}>
          <div style={{ fontSize: 64, marginBottom: 16 }}>✅</div>
          <div style={{ fontSize: 22, fontWeight: 700, color: GREEN, marginBottom: 8 }}>PO Submitted Successfully</div>
          <div style={{ fontSize: 14, color: TEXT_SECONDARY }}>
            Your purchase order for <strong style={{ color: TEXT_PRIMARY }}>{quote.id}</strong> has been received.
            <br />We'll review and confirm within 24 business hours.
          </div>
        </div>
      </div>
    );
  }

  return (
    <div style={{ position: "fixed", inset: 0, background: "rgba(0,0,0,0.7)", display: "flex", alignItems: "center", justifyContent: "center", zIndex: 9999, padding: 20 }}>
      <div style={{
        background: BG_CARD, borderRadius: 16, border: `1px solid ${BORDER}`,
        padding: "36px 32px", maxWidth: 520, width: "100%",
        boxShadow: "0 25px 50px rgba(0,0,0,0.5)", maxHeight: "90vh", overflowY: "auto"
      }}>
        {/* Header */}
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 24 }}>
          <div>
            <div style={{ fontSize: 20, fontWeight: 700, color: TEXT_PRIMARY }}>Upload Purchase Order</div>
            <div style={{ fontSize: 13, color: TEXT_MUTED, marginTop: 4 }}>
              Reference: <span style={{ color: ACCENT, fontFamily: "'JetBrains Mono', monospace" }}>{quote.id}</span>
            </div>
          </div>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 8, border: `1px solid ${BORDER}`,
            background: "transparent", color: TEXT_MUTED, cursor: "pointer", fontSize: 16,
            display: "flex", alignItems: "center", justifyContent: "center"
          }}>✕</button>
        </div>

        {/* Quote Summary */}
        <div style={{ background: BG_INPUT, borderRadius: 10, padding: 16, marginBottom: 20, border: `1px solid ${BORDER}` }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: TEXT_MUTED, textTransform: "uppercase", letterSpacing: "0.05em", marginBottom: 10 }}>
            Quote Summary
          </div>
          {quote.items.map((item, i) => {
            const qty = item.qty || item.quantity || 1;
            const price = item.price || item.unitPrice || item.totalPrice || 0;
            const lineTotal = qty * price;
            return (
            <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "4px 0", fontSize: 13, color: TEXT_SECONDARY }}>
              <span>{qty}× {item.name}</span>
              <span style={{ color: price ? TEXT_PRIMARY : TEXT_MUTED, fontFamily: "'JetBrains Mono', monospace" }}>
                {price ? `$${lineTotal.toLocaleString()}` : "—"}
              </span>
            </div>
            );
          })}
          <div style={{ borderTop: `1px solid ${BORDER}`, marginTop: 10, paddingTop: 10, display: "flex", justifyContent: "space-between", fontSize: 15, fontWeight: 700, color: TEXT_PRIMARY }}>
            <span>Total</span>
            <span style={{ color: ACCENT, fontFamily: "'JetBrains Mono', monospace" }}>${quote.total.toLocaleString()}</span>
          </div>
        </div>

        {/* Upload Zone */}
        <div
          onDragOver={e => { e.preventDefault(); setDragOver(true); }}
          onDragLeave={() => setDragOver(false)}
          onDrop={handleDrop}
          onClick={() => fileRef.current?.click()}
          style={{
            border: `2px dashed ${dragOver ? ACCENT : file ? GREEN : BORDER}`,
            borderRadius: 12, padding: "32px 20px", textAlign: "center",
            cursor: "pointer", marginBottom: 16, transition: "all 0.2s",
            background: dragOver ? `${ACCENT}08` : file ? `${GREEN}08` : "transparent"
          }}
        >
          <input ref={fileRef} type="file" accept=".pdf,application/pdf"
            onChange={e => e.target.files[0] && handleFile(e.target.files[0])}
            style={{ display: "none" }} />
          {file ? (
            <>
              <div style={{ fontSize: 36, marginBottom: 8 }}>📄</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: GREEN }}>{file.name}</div>
              <div style={{ fontSize: 12, color: TEXT_MUTED, marginTop: 4 }}>
                {(file.size / 1024).toFixed(0)} KB — Click to change
              </div>
            </>
          ) : (
            <>
              <div style={{ fontSize: 36, marginBottom: 8 }}>📤</div>
              <div style={{ fontSize: 14, fontWeight: 600, color: TEXT_SECONDARY }}>Drag & drop your PO here</div>
              <div style={{ fontSize: 12, color: TEXT_MUTED, marginTop: 4 }}>PDF only · Max 10MB</div>
            </>
          )}
        </div>

        {/* Upload progress bar */}
        {uploading && (
          <div style={{ marginBottom: 16 }}>
            <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, color: TEXT_MUTED, marginBottom: 6 }}>
              <span>Uploading...</span><span>{uploadProgress}%</span>
            </div>
            <div style={{ background: BORDER, borderRadius: 4, height: 6, overflow: "hidden" }}>
              <div style={{ width: `${uploadProgress}%`, height: "100%", background: ACCENT, transition: "width 0.3s", borderRadius: 4 }} />
            </div>
          </div>
        )}

        {/* Notes */}
        <textarea placeholder="Notes (optional) — shipping instructions, special terms, etc."
          value={notes} onChange={e => setNotes(e.target.value)}
          style={{
            width: "100%", padding: "12px 14px", borderRadius: 8,
            border: `1px solid ${BORDER}`, background: BG_INPUT, color: TEXT_PRIMARY,
            fontSize: 13, fontFamily: "'DM Sans', sans-serif", outline: "none",
            resize: "vertical", minHeight: 70, boxSizing: "border-box"
          }} />

        {error && (
          <div style={{ marginTop: 12, padding: "10px 14px", borderRadius: 8, background: "#ef444420", color: RED, fontSize: 13, fontWeight: 500 }}>
            ⚠ {error}
          </div>
        )}

        {/* Actions */}
        <div style={{ display: "flex", gap: 10, marginTop: 20 }}>
          <button onClick={onClose} style={{
            flex: 1, padding: "12px 0", borderRadius: 8, border: `1px solid ${BORDER}`,
            background: "transparent", color: TEXT_MUTED, cursor: "pointer",
            fontSize: 14, fontWeight: 600, fontFamily: "inherit"
          }}>Cancel</button>
          <button onClick={handleUpload} disabled={!file || uploading} style={{
            flex: 2, padding: "12px 0", borderRadius: 8, border: "none",
            background: !file || uploading ? TEXT_MUTED : ACCENT,
            color: "#0a0f1a", cursor: !file || uploading ? "not-allowed" : "pointer",
            fontSize: 14, fontWeight: 700, fontFamily: "inherit", transition: "all 0.2s"
          }}>
            {uploading ? `Uploading ${uploadProgress}%...` : "Submit Purchase Order"}
          </button>
        </div>
        <div style={{ marginTop: 16, fontSize: 11, color: TEXT_MUTED, textAlign: "center" }}>
          🔒 Files are encrypted and stored securely. Only authorized staff can access uploaded documents.
        </div>
      </div>
    </div>
  );
}


// ── Quote HTML Generator ──
function generateQuoteHTML(order) {
  const date = order.createdAt?.toDate ? order.createdAt.toDate().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" }) : new Date().toLocaleDateString("en-US", { year: "numeric", month: "long", day: "numeric" });
  const items = Array.isArray(order.items)
    ? order.items
    : (typeof order.items === "string" ? order.items.split(",").map(n => ({ name: n.trim(), qty: 1, price: 0 })) : []);

  const lineItems = items.map(item => {
    const qty = item.qty || item.quantity || 1;
    const price = item.price || item.unitPrice || 0;
    const total = qty * price;
    return `
      <tr>
        <td style="padding: 12px 16px; border-bottom: 1px solid #e5e7eb; font-size: 14px; color: #111827;">${item.name || item}</td>
        <td style="padding: 12px 16px; border-bottom: 1px solid #e5e7eb; font-size: 14px; text-align: center; color: #374151;">${qty}</td>
        <td style="padding: 12px 16px; border-bottom: 1px solid #e5e7eb; font-size: 14px; text-align: right; color: #374151; font-family: monospace;">${price ? "$" + price.toLocaleString() : "—"}</td>
        <td style="padding: 12px 16px; border-bottom: 1px solid #e5e7eb; font-size: 14px; text-align: right; font-weight: 600; color: #111827; font-family: monospace;">${total ? "$" + total.toLocaleString() : "—"}</td>
      </tr>`;
  }).join("");

  return `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Quote ${order.quoteId} — ModuSystems</title>
  <style>
    * { margin: 0; padding: 0; box-sizing: border-box; }
    body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; background: #f9fafb; color: #111827; padding: 40px 20px; }
    .page { max-width: 800px; margin: 0 auto; background: #fff; border-radius: 12px; box-shadow: 0 4px 24px rgba(0,0,0,0.08); overflow: hidden; }
    .header { background: #0a0f1a; padding: 36px 48px; display: flex; justify-content: space-between; align-items: flex-start; }
    .logo { font-size: 28px; font-weight: 800; letter-spacing: -0.03em; color: #fff; }
    .logo span { color: #f59e0b; }
    .quote-label { text-align: right; }
    .quote-label .title { font-size: 13px; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.08em; }
    .quote-label .number { font-size: 22px; font-weight: 700; color: #f59e0b; font-family: monospace; margin-top: 4px; }
    .meta { padding: 32px 48px; display: grid; grid-template-columns: 1fr 1fr; gap: 32px; border-bottom: 1px solid #e5e7eb; }
    .meta-group .label { font-size: 11px; font-weight: 700; color: #9ca3af; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 6px; }
    .meta-group .value { font-size: 14px; color: #111827; font-weight: 500; }
    .items { padding: 32px 48px; }
    .items h3 { font-size: 13px; font-weight: 700; color: #6b7280; text-transform: uppercase; letter-spacing: 0.06em; margin-bottom: 16px; }
    table { width: 100%; border-collapse: collapse; }
    thead tr { background: #f3f4f6; }
    thead th { padding: 10px 16px; text-align: left; font-size: 11px; font-weight: 700; color: #6b7280; text-transform: uppercase; letter-spacing: 0.05em; }
    thead th:nth-child(2) { text-align: center; }
    thead th:nth-child(3), thead th:nth-child(4) { text-align: right; }
    .total-row { padding: 20px 48px; background: #f9fafb; border-top: 2px solid #e5e7eb; display: flex; justify-content: flex-end; align-items: center; gap: 24px; }
    .total-label { font-size: 15px; font-weight: 600; color: #374151; }
    .total-amount { font-size: 28px; font-weight: 800; color: #f59e0b; font-family: monospace; }
    .footer { padding: 24px 48px; background: #0a0f1a; text-align: center; }
    .footer p { font-size: 12px; color: #6b7280; }
    .footer a { color: #f59e0b; text-decoration: none; }
    .status-badge { display: inline-block; padding: 4px 12px; border-radius: 20px; background: #fef3c7; color: #d97706; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; margin-top: 6px; }
    @media print { body { background: white; padding: 0; } .page { box-shadow: none; border-radius: 0; } }
  </style>
</head>
<body>
  <div class="page">
    <div class="header">
      <div class="logo"><span>MODU</span>SYSTEMS</div>
      <div class="quote-label">
        <div class="title">Quote</div>
        <div class="number">${order.quoteId}</div>
      </div>
    </div>

    <div class="meta">
      <div class="meta-group">
        <div class="label">Bill To</div>
        <div class="value">${order.customer || "Customer"}</div>
        <div class="value" style="color: #6b7280; font-size: 13px; margin-top: 2px;">${order.customerEmail || ""}</div>
      </div>
      <div class="meta-group">
        <div class="label">Quote Details</div>
        <div class="value">Date: ${date}</div>
        <div class="value" style="margin-top: 4px;">Valid for 30 days</div>
        <div class="status-badge">Awaiting PO</div>
      </div>
    </div>

    <div class="items">
      <h3>Line Items</h3>
      <table>
        <thead>
          <tr>
            <th>Description</th>
            <th>Qty</th>
            <th>Unit Price</th>
            <th>Total</th>
          </tr>
        </thead>
        <tbody>
          ${lineItems}
        </tbody>
      </table>
    </div>

    <div class="total-row">
      <div class="total-label">Total</div>
      <div class="total-amount">$${(order.total || 0).toLocaleString()}</div>
    </div>

    ${order.notes ? `<div style="padding: 16px 48px; background: #fffbeb; border-top: 1px solid #fde68a;"><p style="font-size: 13px; color: #92400e;"><strong>Notes:</strong> ${order.notes}</p></div>` : ""}

    <div class="footer">
      <p>ModuSystems · <a href="https://ai.modusystems.com">ai.modusystems.com</a> · Questions? Reply to this quote or contact g2motion1@gmail.com</p>
    </div>
  </div>
</body>
</html>`;
}

function handleViewQuote(order) {
  const html = generateQuoteHTML(order);
  const blob = new Blob([html], { type: "text/html" });
  const url = URL.createObjectURL(blob);
  window.open(url, "_blank");
}

// ── Admin Review Panel ──
function AdminPanel({ user }) {
  const [pendingOrders, setPendingOrders] = useState([]);
  const [loading, setLoading] = useState(true);
  const [actionMsg, setActionMsg] = useState("");

  useEffect(() => {
    const unsub = db.collection("orders")
      .where("status", "==", "po_uploaded")
      .orderBy("createdAt", "desc")
      .onSnapshot(snap => {
        setPendingOrders(snap.docs.map(d => ({ firestoreId: d.id, ...d.data() })));
        setLoading(false);
      }, err => {
        console.error("Admin load error:", err);
        setLoading(false);
      });
    return () => unsub();
  }, []);

  const handleApprove = async (order) => {
    try {
      await db.collection("orders").doc(order.firestoreId).update({
        status: "approved",
        reviewedAt: firebase.firestore.FieldValue.serverTimestamp(),
        reviewedBy: user.email
      });
      // Send approval email to customer
      await sendEmail(EMAILJS_TEMPLATE_APPROVED, {
        to_email: order.customerEmail,
        to_name: order.customer || order.customerEmail,
        quote_id: order.quoteId,
        order_total: `$${(order.total || 0).toLocaleString()}`,
        items: order.items || "",
        reply_to: ADMIN_NOTIFY_EMAIL,
      });
      setActionMsg(`✅ Order ${order.quoteId} approved${EMAILJS_SERVICE_ID !== 'YOUR_SERVICE_ID' ? ' — customer notified' : ' — configure EmailJS to notify customer'}`);
      setTimeout(() => setActionMsg(""), 4000);
    } catch (err) {
      setActionMsg("Error: " + err.message);
    }
  };

  const handleReject = async (order) => {
    try {
      await db.collection("orders").doc(order.firestoreId).update({
        status: "rejected",
        reviewedAt: firebase.firestore.FieldValue.serverTimestamp(),
        reviewedBy: user.email
      });
      // Send rejection email to customer
      await sendEmail(EMAILJS_TEMPLATE_REJECTED, {
        to_email: order.customerEmail,
        to_name: order.customer || order.customerEmail,
        quote_id: order.quoteId,
        order_total: `$${(order.total || 0).toLocaleString()}`,
        reply_to: ADMIN_NOTIFY_EMAIL,
      });
      setActionMsg(`❌ Order ${order.quoteId} rejected${EMAILJS_SERVICE_ID !== 'YOUR_SERVICE_ID' ? ' — customer notified' : ' — configure EmailJS to notify customer'}`);
      setTimeout(() => setActionMsg(""), 4000);
    } catch (err) {
      setActionMsg("Error: " + err.message);
    }
  };

  const handleViewPDF = async (order) => {
    try {
      const url = await storage.ref(order.poStoragePath).getDownloadURL();
      window.open(url, "_blank");
    } catch (err) {
      alert("Could not load PDF: " + err.message);
    }
  };

  return (
    <div style={{ background: BG_CARD, borderRadius: 12, border: `1px solid ${BORDER}`, padding: 24, marginBottom: 24 }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 16 }}>
        <div style={{ fontSize: 16, fontWeight: 700, color: TEXT_PRIMARY }}>Admin Review Queue</div>
        <span style={{
          padding: "4px 12px", borderRadius: 20,
          background: pendingOrders.length > 0 ? "#ef444420" : `${GREEN}20`,
          color: pendingOrders.length > 0 ? RED : GREEN,
          fontSize: 12, fontWeight: 700
        }}>
          {pendingOrders.length} pending
        </span>
      </div>

      {actionMsg && (
        <div style={{ marginBottom: 12, padding: "10px 14px", borderRadius: 8, background: `${GREEN}20`, color: GREEN, fontSize: 13, fontWeight: 500 }}>
          {actionMsg}
        </div>
      )}

      {loading ? (
        <div style={{ textAlign: "center", padding: "24px 0", color: TEXT_MUTED }}>Loading orders...</div>
      ) : pendingOrders.length === 0 ? (
        <div style={{ textAlign: "center", padding: "24px 0", color: TEXT_MUTED, fontSize: 14 }}>
          No purchase orders awaiting review
        </div>
      ) : (
        pendingOrders.map(order => (
          <div key={order.firestoreId} style={{
            background: BG_INPUT, borderRadius: 10, padding: 16, marginBottom: 10,
            border: `1px solid ${BORDER}`
          }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginBottom: 8 }}>
              <div>
                <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 13, color: ACCENT, fontWeight: 600 }}>
                  {order.quoteId}
                </span>
                <span style={{ color: TEXT_MUTED, fontSize: 12, marginLeft: 8 }}>
                  {order.createdAt?.toDate ? order.createdAt.toDate().toLocaleDateString() : ""}
                </span>
              </div>
              <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 15, fontWeight: 700, color: TEXT_PRIMARY }}>
                ${order.total?.toLocaleString()}
              </span>
            </div>
            <div style={{ fontSize: 12, color: TEXT_SECONDARY, marginBottom: 4 }}>
              📄 {order.poFileName} · {order.customer}
            </div>
            <div style={{ fontSize: 12, color: TEXT_MUTED, marginBottom: 8 }}>
              ✉ {order.customerEmail}
            </div>
            {order.notes && (
              <div style={{ fontSize: 12, color: TEXT_MUTED, fontStyle: "italic", marginBottom: 8 }}>
                "{order.notes}"
              </div>
            )}
            <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
              <button onClick={() => handleApprove(order)} style={{
                flex: 1, padding: "8px 0", borderRadius: 6, border: "none",
                background: GREEN, color: "#fff", fontSize: 12, fontWeight: 700,
                cursor: "pointer", fontFamily: "inherit"
              }}>Approve & Process</button>
              <button onClick={() => handleReject(order)} style={{
                flex: 1, padding: "8px 0", borderRadius: 6, border: `1px solid ${BORDER}`,
                background: "transparent", color: RED, fontSize: 12, fontWeight: 700,
                cursor: "pointer", fontFamily: "inherit"
              }}>Reject</button>
              <button onClick={() => handleViewQuote(order)} style={{
                padding: "8px 16px", borderRadius: 6, border: `1px solid ${ACCENT}`,
                background: "transparent", color: ACCENT, fontSize: 12, fontWeight: 600,
                cursor: "pointer", fontFamily: "inherit"
              }}>View Quote</button>
              <button onClick={() => handleViewPDF(order)} style={{
                padding: "8px 16px", borderRadius: 6, border: `1px solid ${BORDER}`,
                background: "transparent", color: TEXT_MUTED, fontSize: 12, fontWeight: 600,
                cursor: "pointer", fontFamily: "inherit"
              }}>View PO</button>
            </div>
          </div>
        ))
      )}
    </div>
  );
}

// ── Main Portal ──
function OrderPortal() {
  const [user, setUser] = useState(null);
  const [authChecked, setAuthChecked] = useState(false);
  const [view, setView] = useState("quotes");
  const [quotes, setQuotes] = useState([]);
  const [orders, setOrders] = useState([]);
  const [loadingQuotes, setLoadingQuotes] = useState(false);
  const [uploadQuote, setUploadQuote] = useState(null);

  const PAY_THRESHOLD = 5000;

  // Check if already signed in on page load
  useEffect(() => {
    const unsub = auth.onAuthStateChanged(async (firebaseUser) => {
      if (firebaseUser) {
        let custData = {};
        const custDoc = await db.collection("customers").doc(firebaseUser.uid).get();
        if (custDoc.exists) {
          custData = custDoc.data();
        } else {
          // Fall back to users collection (created via index.html)
          const userDoc = await db.collection("users").doc(firebaseUser.uid).get();
          if (userDoc.exists) custData = { company: userDoc.data().name, ...userDoc.data() };
        }
        setUser({
          email: firebaseUser.email,
          company: custData.company || custData.name || firebaseUser.email.split("@")[0],
          uid: firebaseUser.uid
        });
      } else {
        setUser(null);
      }
      setAuthChecked(true);
    });
    return () => unsub();
  }, []);

  // Load quotes from Firestore when user logs in
  useEffect(() => {
    if (!user) { setQuotes([]); setOrders([]); return; }
    setLoadingQuotes(true);

    // Real-time listener for quotes — handles both customerEmail (new) and userEmail (legacy)
    const unsubQuotes = db.collection("quotes")
      .where("customerEmail", "==", user.email)
      .orderBy("createdAt", "desc")
      .onSnapshot(snap => {
        const newQuotes = snap.docs.map(d => ({ firestoreId: d.id, ...d.data() }));
        // Also query legacy userEmail field and merge
        db.collection("quotes")
          .where("userEmail", "==", user.email)
          .orderBy("createdAt", "desc")
          .get()
          .then(legacySnap => {
            const legacyIds = new Set(newQuotes.map(q => q.firestoreId));
            const legacyQuotes = legacySnap.docs
              .filter(d => !legacyIds.has(d.id))
              .map(d => {
                const data = d.data();
                return {
                  firestoreId: d.id,
                  ...data,
                  // Normalize field names for portal compatibility
                  customerEmail: data.customerEmail || data.userEmail,
                  total: data.total || data.totalPrice || 0,
                  id: data.id || data.quoteNumber || d.id,
                  status: data.status || "pending"
                };
              });
            setQuotes([...newQuotes, ...legacyQuotes]);
            setLoadingQuotes(false);
          })
          .catch(() => {
            setQuotes(newQuotes);
            setLoadingQuotes(false);
          });
      }, err => {
        console.error("Quotes load error:", err);
        setLoadingQuotes(false);
      });

    // Real-time listener for orders
    const unsubOrders = db.collection("orders")
      .where("customerEmail", "==", user.email)
      .orderBy("createdAt", "desc")
      .onSnapshot(snap => {
        setOrders(snap.docs.map(d => ({ firestoreId: d.id, ...d.data() })));
      }, err => {
        console.error("Orders load error:", err);
      });

    return () => { unsubQuotes(); unsubOrders(); };
  }, [user]);

  const handleLogin = (userData) => setUser(userData);

  const handleSignOut = async () => {
    await auth.signOut();
    setUser(null);
  };

  const handlePOUpload = (quoteId, fileName) => {
    setUploadQuote(null);
    // Data updates automatically via Firestore listeners
  };

  const isAdmin = user && ADMIN_EMAILS.includes(user.email);

  // Show loading spinner while checking auth state
  if (!authChecked) {
    return (
      <div style={{ minHeight: "100vh", background: BG_DARK, display: "flex", alignItems: "center", justifyContent: "center" }}>
        <div style={{ fontSize: 14, color: TEXT_MUTED, fontFamily: "'DM Sans', sans-serif" }}>Loading...</div>
      </div>
    );
  }

  if (!user) return <AuthScreen onLogin={handleLogin} />;

  return (
    <div style={{ minHeight: "100vh", background: BG_DARK, fontFamily: "'DM Sans', sans-serif", color: TEXT_PRIMARY }}>
      <link href="https://fonts.googleapis.com/css2?family=DM+Sans:wght@400;500;600;700&family=JetBrains+Mono:wght@500&display=swap" rel="stylesheet" />

      {/* Top Bar */}
      <div style={{
        background: BG_CARD, borderBottom: `1px solid ${BORDER}`,
        padding: "0 32px", display: "flex", alignItems: "center",
        justifyContent: "space-between", height: 64
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 24 }}>
          <div style={{ fontSize: 22, fontWeight: 800, letterSpacing: "-0.03em" }}>
            <span style={{ color: ACCENT }}>MODU</span>SYSTEMS
            <span style={{ color: TEXT_MUTED, fontSize: 13, fontWeight: 500, marginLeft: 8 }}>Order Portal</span>
          </div>
          <div style={{ display: "flex", gap: 0, marginLeft: 16, borderRadius: 8, overflow: "hidden", border: `1px solid ${BORDER}` }}>
            {[
              { key: "quotes", label: "Quotes", icon: "📋" },
              { key: "orders", label: "Orders", icon: "📦" },
              ...(isAdmin ? [{ key: "admin", label: "Admin", icon: "⚙️" }] : [])
            ].map(tab => (
              <button key={tab.key} onClick={() => setView(tab.key)}
                style={{
                  padding: "8px 18px", border: "none", cursor: "pointer",
                  background: view === tab.key ? ACCENT : "transparent",
                  color: view === tab.key ? "#0a0f1a" : TEXT_MUTED,
                  fontWeight: 600, fontSize: 12, fontFamily: "inherit",
                  transition: "all 0.15s"
                }}>
                {tab.icon} {tab.label}
              </button>
            ))}
          </div>
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ textAlign: "right" }}>
            <div style={{ fontSize: 13, fontWeight: 600, color: TEXT_PRIMARY }}>{user.company}</div>
            <div style={{ fontSize: 11, color: TEXT_MUTED }}>{user.email}</div>
          </div>
          <button onClick={handleSignOut} style={{
            padding: "6px 14px", borderRadius: 6, border: `1px solid ${BORDER}`,
            background: "transparent", color: TEXT_MUTED, cursor: "pointer",
            fontSize: 11, fontWeight: 600, fontFamily: "inherit"
          }}>Sign Out</button>
        </div>
      </div>

      {/* Content */}
      <div style={{ maxWidth: 900, margin: "0 auto", padding: "32px 24px" }}>

        {/* QUOTES VIEW */}
        {view === "quotes" && (
          <>
            <div style={{ fontSize: 12, fontWeight: 700, color: TEXT_MUTED, textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 16 }}>
              Open Quotes
            </div>
            {loadingQuotes ? (
              <div style={{ textAlign: "center", padding: 48, color: TEXT_MUTED }}>
                <div style={{ fontSize: 14 }}>Loading quotes...</div>
              </div>
            ) : quotes.filter(q => q.status === "pending" || q.status === "po_uploaded").length === 0 ? (
              <div style={{ textAlign: "center", padding: 48, color: TEXT_MUTED }}>
                <div style={{ fontSize: 48, marginBottom: 12 }}>📋</div>
                <div style={{ fontSize: 15 }}>No open quotes</div>
                <div style={{ fontSize: 13, marginTop: 4 }}>Configure a system in the platform to generate a quote</div>
              </div>
            ) : (
              quotes
                .filter(q => q.status === "pending" || q.status === "po_uploaded")
                .map(quote => (
                  <div key={quote.firestoreId || quote.id} style={{
                    background: BG_CARD, borderRadius: 12, border: `1px solid ${BORDER}`,
                    padding: 20, marginBottom: 12, transition: "border-color 0.2s"
                  }}>
                    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", marginBottom: 12 }}>
                      <div>
                        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                          <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 15, fontWeight: 700, color: TEXT_PRIMARY }}>
                            {quote.id}
                          </span>
                          <StatusBadge status={quote.status} />
                        </div>
                        <div style={{ fontSize: 12, color: TEXT_MUTED }}>
                          Created {quote.date || (quote.createdAt?.toDate ? quote.createdAt.toDate().toLocaleDateString() : "")} · {(quote.items || []).length} item{(quote.items || []).length !== 1 ? "s" : ""}
                        </div>
                      </div>
                      <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 20, fontWeight: 700, color: ACCENT }}>
                        ${(quote.total || quote.totalPrice || 0).toLocaleString()}
                      </div>
                    </div>

                    {/* Line items */}
                    <div style={{ background: BG_INPUT, borderRadius: 8, padding: 12, marginBottom: 14, border: `1px solid ${BORDER}` }}>
                      {(quote.items || []).map((item, i) => {
                        const qty = item.qty || item.quantity || 1;
                        const price = item.price || item.unitPrice || 0;
                        const lineTotal = qty * price;
                        return (
                        <div key={i} style={{ display: "flex", justifyContent: "space-between", padding: "3px 0", fontSize: 13, color: TEXT_SECONDARY }}>
                          <span>{qty}× {item.name}</span>
                          <span style={{ fontFamily: "'JetBrains Mono', monospace", color: TEXT_PRIMARY }}>
                            {price ? `$${lineTotal.toLocaleString()}` : "—"}
                          </span>
                        </div>
                        );
                      })}
                    </div>

                    {/* Actions */}
                    {quote.status === "pending" && (
                      <div style={{ display: "flex", gap: 10 }}>
                        {quote.total <= PAY_THRESHOLD ? (
                          <>
                            <button style={{
                              flex: 1, padding: "10px 0", borderRadius: 8, border: "none",
                              background: GREEN, color: "#fff", fontSize: 13, fontWeight: 700,
                              cursor: "pointer", fontFamily: "inherit"
                            }}>
                              💳 Pay Now — ${(quote.total || quote.totalPrice || 0).toLocaleString()}
                            </button>
                            <button onClick={() => setUploadQuote(quote)} style={{
                              flex: 1, padding: "10px 0", borderRadius: 8,
                              border: `1px solid ${BORDER}`, background: "transparent",
                              color: TEXT_SECONDARY, fontSize: 13, fontWeight: 600,
                              cursor: "pointer", fontFamily: "inherit"
                            }}>
                              📤 Upload PO Instead
                            </button>
                          </>
                        ) : (
                          <>
                            <button onClick={() => setUploadQuote(quote)} style={{
                              flex: 1, padding: "10px 0", borderRadius: 8, border: "none",
                              background: ACCENT, color: "#0a0f1a", fontSize: 13, fontWeight: 700,
                              cursor: "pointer", fontFamily: "inherit"
                            }}>
                              📤 Upload Purchase Order
                            </button>
                            <button style={{
                              padding: "10px 20px", borderRadius: 8,
                              border: `1px solid ${BORDER}`, background: "transparent",
                              color: TEXT_MUTED, fontSize: 13, fontWeight: 600,
                              cursor: "pointer", fontFamily: "inherit"
                            }}>
                              📥 Download Quote PDF
                            </button>
                          </>
                        )}
                      </div>
                    )}
                    {quote.status === "po_uploaded" && (
                      <div style={{ fontSize: 13, color: BLUE, fontWeight: 500 }}>
                        ✓ Purchase order submitted — under review
                      </div>
                    )}
                  </div>
                ))
            )}
          </>
        )}

        {/* ORDERS VIEW */}
        {view === "orders" && (
          <>
            <div style={{ fontSize: 12, fontWeight: 700, color: TEXT_MUTED, textTransform: "uppercase", letterSpacing: "0.08em", marginBottom: 16 }}>
              Order History
            </div>
            {orders.length === 0 ? (
              <div style={{ textAlign: "center", padding: 48, color: TEXT_MUTED }}>
                <div style={{ fontSize: 48, marginBottom: 12 }}>📦</div>
                <div style={{ fontSize: 15 }}>No orders yet</div>
              </div>
            ) : (
              orders.map(order => (
                <div key={order.firestoreId} style={{
                  background: BG_CARD, borderRadius: 12, border: `1px solid ${BORDER}`,
                  padding: 20, marginBottom: 10
                }}>
                  <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
                    <div>
                      <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 4 }}>
                        <span style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 14, fontWeight: 700, color: TEXT_PRIMARY }}>
                          {order.id || order.quoteId}
                        </span>
                        <span style={{ fontSize: 12, color: TEXT_MUTED }}>ref: {order.quoteId}</span>
                        <StatusBadge status={order.status} />
                      </div>
                      <div style={{ fontSize: 13, color: TEXT_SECONDARY, marginTop: 2 }}>{order.items}</div>
                      <div style={{ fontSize: 12, color: TEXT_MUTED, marginTop: 2 }}>
                        Ordered {order.createdAt?.toDate ? order.createdAt.toDate().toLocaleDateString() : order.date || ""}
                        {order.tracking && (
                          <span> · Tracking: <span style={{ color: BLUE, fontFamily: "'JetBrains Mono', monospace" }}>{order.tracking}</span></span>
                        )}
                      </div>
                    </div>
                    <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 17, fontWeight: 700, color: ACCENT }}>
                      ${(order.total || 0).toLocaleString()}
                    </div>
                  </div>
                </div>
              ))
            )}
          </>
        )}

        {/* ADMIN VIEW */}
        {view === "admin" && isAdmin && (
          <AdminPanel user={user} />
        )}
      </div>

      {/* Modals */}
      {uploadQuote && (
        <POUploadModal
          quote={uploadQuote}
          user={user}
          onClose={() => setUploadQuote(null)}
          onUpload={handlePOUpload}
        />
      )}
    </div>
  );
}
