import { createFileRoute, Link } from "@tanstack/react-router";
import { useState, useRef, useEffect } from "react";

export const Route = createFileRoute("/shop")({
  head: () => ({
    meta: [
      { title: "Shop — Shopify VA Made Easy" },
      { name: "description", content: "Browse digital products for aspiring Shopify VAs." },
    ],
  }),
  component: ShopPage,
});

/* ─── Types ──────────────────────────────────────────────────────────────── */
type Product = typeof PRODUCTS[0];
type CartItem = { product: Product; qty: number };
type View = "shop" | "checkout" | "thankyou";
type PayMethod = "gcash" | "bpi" | "bdo" | "qr" | null;

/* ─── Product data ───────────────────────────────────────────────────────── */
const PRODUCTS = [
  {
    id: 1, badge: "Best Seller", badgeColor: "green", category: "Bundle",
    name: "Shopify VA Career Accelerator",
    desc: "Everything in Tier 1, plus done-for-you documents written for your background.",
    price: 1499, original: 2999, savings: 73, rating: 5, reviews: 214, tag: "Most Popular",
    includes: ["Personalized ATS Resume (OLJ)", "Personalized ATS Resume (Upwork)", "Customized Cover Letter", "Portfolio Canva Template", "Interview Prep Guide (30 Q&As)", "VA Skills Roadmap", "30-Day Client-Getting Action Plan"],
    emoji: "🚀", gradient: "linear-gradient(135deg,#0d9488 0%,#0a3d62 100%)",
  },
  {
    id: 2, badge: "New", badgeColor: "blue", category: "Course",
    name: "Shopify VA Starter Kit",
    desc: "Self-paced essentials to launch your VA career and land your first client.",
    price: 499, original: 999, savings: 50, rating: 5, reviews: 189, tag: null,
    includes: ["Shopify VA Mini Course (10 self-paced modules)", "ATS Resume Template", "Shopify VA Resume Sample", "Winning Proposal Templates (3 versions)", "Client Outreach Scripts", "List of Websites to Find Clients"],
    emoji: "🎓", gradient: "linear-gradient(135deg,#f59e0b 0%,#d97706 100%)",
  },
  {
    id: 3, badge: null, badgeColor: null, category: "Template",
    name: "ATS Resume Template",
    desc: "Recruiter-approved, ATS-optimized resume template formatted for Onlinejobs.ph and Upwork.",
    price: 299, original: 599, savings: 50, rating: 5, reviews: 312, tag: null,
    includes: ["Canva + Google Docs Format", "OLJ Version", "Upwork Version", "Video Tutorial"],
    emoji: "📄", gradient: "linear-gradient(135deg,#6d28d9 0%,#4c1d95 100%)",
  },
  {
    id: 4, badge: null, badgeColor: null, category: "Template",
    name: "Winning Proposal Pack",
    desc: "3 proven proposal templates that get replies. Includes cold outreach scripts and a client follow-up sequence.",
    price: 199, original: 399, savings: 50, rating: 4.9, reviews: 178, tag: null,
    includes: ["3 Proposal Templates", "Cold Outreach Scripts", "Follow-Up Sequence", "Real Client Examples"],
    emoji: "✍️", gradient: "linear-gradient(135deg,#0ea5e9 0%,#0284c7 100%)",
  },
  {
    id: 5, badge: "VIP", badgeColor: "purple", category: "Live Course",
    name: "Shopify VA Launch Accelerator",
    desc: "A 30-day live group masterclass — real coaching, walkthroughs & Q&A with your instructor.",
    price: 3999, original: 5000, savings: 20, rating: 5, reviews: 56, tag: "Limited Slots",
    includes: ["Live Group Coaching Sessions (screen-shared)", "Practical Shopify Training (taught live)", "Live Q&A Every Session", "30 Days of Structured Learning", "Small Batch Format (limited slots)", "Certificate of Completion", "Exclusive Alumni Community Access"],
    emoji: "⚡", gradient: "linear-gradient(135deg,#dc2626 0%,#991b1b 100%)",
  },
  {
    id: 6, badge: null, badgeColor: null, category: "Guide",
    name: "Interview Prep Guide",
    desc: "30 real interview Q&As asked by Shopify store owners, with sample answers written for VA applicants.",
    price: 149, original: 299, savings: 50, rating: 4.8, reviews: 94, tag: null,
    includes: ["30 Real Q&As", "Sample Answers", "Tips & Red Flags", "PDF Format"],
    emoji: "💬", gradient: "linear-gradient(135deg,#059669 0%,#047857 100%)",
  },
];

const CATEGORIES = ["All", "Bundle", "Course", "Template", "Guide", "Live Course"];

const PAYMENT_METHODS = [
  { id: "gcash" as PayMethod, label: "GCash", icon: "📱", number: "0917-123-4567", name: "Mary A." },
  { id: "bpi"   as PayMethod, label: "BPI",   icon: "🏦", number: "1234-5678-90",  name: "Mary A." },
  { id: "bdo"   as PayMethod, label: "BDO",   icon: "🏦", number: "0012-3456-789", name: "Mary A." },
  { id: "qr"    as PayMethod, label: "QR Code", icon: "📷", number: null,          name: null },
];

/* ─── Small helpers ──────────────────────────────────────────────────────── */
function Stars({ rating }: { rating: number }) {
  return (
    <span className="shop-stars" aria-label={`${rating} out of 5 stars`}>
      {[1,2,3,4,5].map((s) => (
        <svg key={s} viewBox="0 0 20 20" fill={s <= Math.round(rating) ? "currentColor" : "none"} stroke="currentColor">
          <path d="M9.049 2.927c.3-.921 1.603-.921 1.902 0l1.07 3.292a1 1 0 00.95.69h3.462c.969 0 1.371 1.24.588 1.81l-2.8 2.034a1 1 0 00-.364 1.118l1.07 3.292c.3.921-.755 1.688-1.54 1.118l-2.8-2.034a1 1 0 00-1.175 0l-2.8 2.034c-.784.57-1.838-.197-1.539-1.118l1.07-3.292a1 1 0 00-.364-1.118L2.98 8.72c-.783-.57-.38-1.81.588-1.81h3.461a1 1 0 00.951-.69l1.07-3.292z" />
        </svg>
      ))}
    </span>
  );
}

function CartIcon({ size = 22 }: { size?: number }) {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <circle cx="9" cy="21" r="1"/><circle cx="20" cy="21" r="1"/>
      <path d="M1 1h4l2.68 13.39a2 2 0 0 0 2 1.61h9.72a2 2 0 0 0 2-1.61L23 6H6"/>
    </svg>
  );
}

function CheckIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d="M20 6 9 17l-5-5"/>
    </svg>
  );
}

function CloseIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
      <path d="M18 6 6 18M6 6l12 12"/>
    </svg>
  );
}

function TrashIcon() {
  return (
    <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <polyline points="3 6 5 6 21 6"/><path d="M19 6l-1 14a2 2 0 0 1-2 2H8a2 2 0 0 1-2-2L5 6"/>
      <path d="M10 11v6M14 11v6M9 6V4h6v2"/>
    </svg>
  );
}

function generateOrderId() {
  return "SME-" + Date.now().toString(36).toUpperCase().slice(-6);
}

/* ─── Add-to-Cart Modal ───────────────────────────────────────────────────── */
function CartModal({
  product, onClose, onCheckout, cartCount,
}: { product: Product; onClose: () => void; onCheckout: () => void; cartCount: number }) {
  useEffect(() => {
    const handler = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); };
    document.addEventListener("keydown", handler);
    return () => document.removeEventListener("keydown", handler);
  }, [onClose]);

  return (
    <div className="modal-backdrop" role="dialog" aria-modal="true" aria-label="Item added to cart" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="cart-modal">
        <button className="modal-close" onClick={onClose} aria-label="Close"><CloseIcon /></button>

        <div className="cart-modal__check">
          <span aria-hidden="true"><CheckIcon /></span>
        </div>
        <p className="cart-modal__added-label">Added to cart!</p>

        <div className="cart-modal__item">
          <div className="cart-modal__item-visual" style={{ background: product.gradient }}>
            <span aria-hidden="true">{product.emoji}</span>
          </div>
          <div className="cart-modal__item-info">
            <p className="cart-modal__item-name">{product.name}</p>
            <p className="cart-modal__item-price">₱{product.price.toLocaleString()}</p>
          </div>
        </div>

        <p className="cart-modal__count">{cartCount} item{cartCount !== 1 ? "s" : ""} in cart</p>

        <div className="cart-modal__actions">
          <button className="btn cart-modal__btn-checkout" onClick={onCheckout}>
            Proceed to Checkout
          </button>
          <button className="btn cart-modal__btn-continue" onClick={onClose}>
            Continue Shopping
          </button>
        </div>
      </div>
    </div>
  );
}

/* ─── Checkout Page — 3-step wizard ─────────────────────────────────────── */
function CheckoutPage({
  cartItems,
  onBack,
  onComplete,
  onUpdateQty,
}: {
  cartItems: CartItem[];
  onBack: () => void;
  onComplete: (orderId: string, buyer: { name: string; email: string }) => void;
  onUpdateQty: (productId: number, qty: number) => void;
}) {
  const [step, setStep] = useState<1 | 2 | 3>(1);
  const [name,  setName]  = useState("");
  const [email, setEmail] = useState("");
  const [payMethod, setPayMethod]       = useState<PayMethod>(null);
  const [proofFile, setProofFile]       = useState<File | null>(null);
  const [proofPreview, setProofPreview] = useState<string | null>(null);
  const [errors, setErrors]             = useState<Record<string, string>>({});
  const fileRef = useRef<HTMLInputElement>(null);

  const total = cartItems.reduce((s, i) => s + i.product.price * i.qty, 0);
  const selectedMethod = PAYMENT_METHODS.find((m) => m.id === payMethod);

  function scrollTop() { window.scrollTo({ top: 0, behavior: "smooth" }); }

  function handleUpdateQty(productId: number, newQty: number) {
    if (newQty <= 0) {
      if (confirm("Remove this item from your cart?")) {
        onUpdateQty(productId, 0);
      }
    } else {
      onUpdateQty(productId, newQty);
    }
  }

  /* Step 1 → 2 */
  function nextToPayment() {
    const errs: Record<string, string> = {};
    if (!name.trim())  errs.name  = "Full name is required.";
    if (!email.trim() || !/\S+@\S+\.\S+/.test(email)) errs.email = "Valid email is required.";
    setErrors(errs);
    if (Object.keys(errs).length) return;
    setStep(2); scrollTop();
  }

  /* Step 2 → 3 */
  function nextToProof() {
    if (!payMethod) { setErrors({ pay: "Please select a payment method." }); return; }
    setErrors({});
    setStep(3); scrollTop();
  }

  /* Step 3 → submit */
  function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    if (!proofFile) { setErrors({ proof: "Please upload your proof of payment." }); return; }
    onComplete(generateOrderId(), { name: name.trim(), email: email.trim() });
  }

  function handleFile(e: React.ChangeEvent<HTMLInputElement>) {
    const f = e.target.files?.[0];
    if (!f) return;
    setProofFile(f);
    const reader = new FileReader();
    reader.onload = (ev) => setProofPreview(ev.target?.result as string);
    reader.readAsDataURL(f);
  }

  const STEPS = [
    { num: 1, label: "Contact" },
    { num: 2, label: "Payment" },
    { num: 3, label: "Confirm" },
  ];

  return (
    <div className="checkout-page">
      {/* ── Step Progress Bar ── */}
      <div className="co-stepper-wrap">
        <div className="container">
          <div className="co-stepper">
            {STEPS.map((s, i) => (
              <div key={s.num} className={`co-step ${step === s.num ? "co-step--active" : step > s.num ? "co-step--done" : ""}`}>
                <div className="co-step__bubble">
                  {step > s.num
                    ? <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M20 6 9 17l-5-5"/></svg>
                    : s.num}
                </div>
                <span className="co-step__label">{s.label}</span>
                {i < STEPS.length - 1 && <div className={`co-step__line ${step > s.num ? "co-step__line--done" : ""}`} />}
              </div>
            ))}
          </div>
        </div>
      </div>

      <div className="container checkout-layout">
        {/* ── Left: Steps ── */}
        <div className="checkout-form-col">
          <button className="checkout-back" onClick={step === 1 ? onBack : () => { setStep((step - 1) as 1|2|3); scrollTop(); }}>
            <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M19 12H5M12 5l-7 7 7 7"/></svg>
            {step === 1 ? "Back to Shop" : "Previous Step"}
          </button>

          {/* ════ STEP 1: Contact ════ */}
          {step === 1 && (
            <div className="co-step-panel" key="step1">
              <div className="co-step-panel__header">
                <span className="co-step-panel__icon">👤</span>
                <div>
                  <h1 className="checkout-title">Contact Information</h1>
                  <p className="co-step-panel__sub">We&rsquo;ll send your download link here.</p>
                </div>
              </div>
              <div className="checkout-section">
                <div className="checkout-field">
                  <label htmlFor="co-name">Full Name</label>
                  <input id="co-name" type="text" placeholder="Juan dela Cruz"
                    value={name} onChange={(e) => setName(e.target.value)}
                    className={errors.name ? "is-error" : ""} />
                  {errors.name && <span className="field-error">{errors.name}</span>}
                </div>
                <div className="checkout-field" style={{ marginBottom: "1.5rem" }}>
                  <label htmlFor="co-email">Email Address</label>
                  <input id="co-email" type="email" placeholder="juan@email.com"
                    value={email} onChange={(e) => setEmail(e.target.value)}
                    className={errors.email ? "is-error" : ""} />
                  {errors.email && <span className="field-error">{errors.email}</span>}
                </div>

                <button className="btn checkout-submit" onClick={nextToPayment}>
                  Continue to Payment →
                </button>
              </div>
            </div>
          )}

          {/* ════ STEP 2: Payment ════ */}
          {step === 2 && (
            <div className="co-step-panel" key="step2">
              <div className="co-step-panel__header">
                <span className="co-step-panel__icon">💳</span>
                <div>
                  <h1 className="checkout-title">Payment Method</h1>
                  <p className="co-step-panel__sub">Choose how you&rsquo;d like to pay ₱{total.toLocaleString()}.</p>
                </div>
              </div>

              <div className="checkout-section">
                {errors.pay && <span className="field-error co-field-error--top">{errors.pay}</span>}

                <div className="pay-methods">
                  {PAYMENT_METHODS.map((m) => (
                    <button key={m.id!} type="button"
                      className={`pay-method ${payMethod === m.id ? "pay-method--active" : ""}`}
                      onClick={() => { setPayMethod(m.id); setErrors({}); }}>
                      <span className="pay-method__icon">{m.icon}</span>
                      <span className="pay-method__label">{m.label}</span>
                      {payMethod === m.id && <span className="pay-method__check"><CheckIcon /></span>}
                    </button>
                  ))}
                </div>

                {selectedMethod && (
                  <div className="pay-details" style={{ marginBottom: "1.5rem" }}>
                    {selectedMethod.id === "qr" ? (
                      <div className="pay-details__qr-row">
                        <div className="pay-details__qr">
                          <div className="pay-details__qr-box" aria-label="QR Code">
                            <svg viewBox="0 0 80 80" fill="none" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
                              <rect x="2" y="2" width="30" height="30" rx="3" stroke="currentColor" strokeWidth="3"/>
                              <rect x="10" y="10" width="14" height="14" rx="1" fill="currentColor"/>
                              <rect x="48" y="2" width="30" height="30" rx="3" stroke="currentColor" strokeWidth="3"/>
                              <rect x="56" y="10" width="14" height="14" rx="1" fill="currentColor"/>
                              <rect x="2" y="48" width="30" height="30" rx="3" stroke="currentColor" strokeWidth="3"/>
                              <rect x="10" y="56" width="14" height="14" rx="1" fill="currentColor"/>
                              <rect x="48" y="48" width="8" height="8" rx="1" fill="currentColor"/>
                              <rect x="62" y="48" width="8" height="8" rx="1" fill="currentColor"/>
                              <rect x="48" y="62" width="8" height="8" rx="1" fill="currentColor"/>
                              <rect x="62" y="62" width="8" height="8" rx="1" fill="currentColor"/>
                            </svg>
                          </div>
                          <p className="pay-details__qr-note">Scan with your e-wallet to pay <strong>₱{total.toLocaleString()}</strong>.</p>
                        </div>

                        {/* Upload proof right next to QR */}
                        <div className="pay-details__upload-inline">
                          <div className={`proof-upload proof-upload--inline ${proofFile ? "proof-upload--done" : ""}`}
                            onClick={() => fileRef.current?.click()} role="button" tabIndex={0}
                            onKeyDown={(e) => { if (e.key === "Enter") fileRef.current?.click(); }}>
                            <input ref={fileRef} type="file" accept="image/*,.pdf" onChange={handleFile}
                              className="proof-upload__input" aria-label="Upload proof" />
                            {proofPreview ? (
                              <div className="proof-upload__preview">
                                <img src={proofPreview} alt="Proof preview" />
                                <span className="proof-upload__filename">✅ Uploaded</span>
                              </div>
                            ) : (
                              <div className="proof-upload__placeholder">
                                <span className="proof-upload__icon" aria-hidden="true">📎</span>
                                <p>Upload Proof</p>
                                <p className="proof-upload__sub">PNG, JPG, PDF</p>
                              </div>
                            )}
                          </div>
                        </div>
                      </div>
                    ) : (
                      <div className="pay-details__bank">
                        <div className="pay-details__row"><span>Bank / Wallet</span><strong>{selectedMethod.label}</strong></div>
                        <div className="pay-details__row"><span>Account Number</span><strong className="pay-details__acct">{selectedMethod.number}</strong></div>
                        <div className="pay-details__row"><span>Account Name</span><strong>{selectedMethod.name}</strong></div>
                        <div className="pay-details__row pay-details__row--total"><span>Amount to Send</span><strong>₱{total.toLocaleString()}</strong></div>
                      </div>
                    )}
                  </div>
                )}

                <button className="btn checkout-submit" onClick={nextToProof} disabled={!payMethod}>
                  {payMethod ? "I've Sent the Payment →" : "Select a Payment Method"}
                </button>
              </div>
            </div>
          )}

          {/* ════ STEP 3: Proof + Review ════ */}
          {step === 3 && (
            <form className="co-step-panel" key="step3" onSubmit={handleSubmit} noValidate>
              <div className="co-step-panel__header">
                <span className="co-step-panel__icon">📎</span>
                <div>
                  <h1 className="checkout-title">Upload Proof of Payment</h1>
                  <p className="co-step-panel__sub">Attach your transaction screenshot or receipt to confirm your payment.</p>
                </div>
              </div>

              <div className="checkout-section">
                {errors.proof && <span className="field-error co-field-error--top">{errors.proof}</span>}

                <div className={`proof-upload ${proofFile ? "proof-upload--done" : ""}`}
                  style={{ marginBottom: "1.5rem" }}
                  onClick={() => fileRef.current?.click()} role="button" tabIndex={0}
                  onKeyDown={(e) => { if (e.key === "Enter") fileRef.current?.click(); }}>
                  <input ref={fileRef} type="file" accept="image/*,.pdf" onChange={handleFile}
                    className="proof-upload__input" aria-label="Upload proof of payment" />
                  {proofPreview ? (
                    <div className="proof-upload__preview">
                      <img src={proofPreview} alt="Proof of payment preview" />
                      <span className="proof-upload__filename">✅ {proofFile?.name}</span>
                      <span className="proof-upload__change">Click to change</span>
                    </div>
                  ) : (
                    <div className="proof-upload__placeholder">
                      <span className="proof-upload__icon" aria-hidden="true">📎</span>
                      <p>Click to upload receipt</p>
                      <p className="proof-upload__sub">PNG, JPG, or PDF — max 10 MB</p>
                    </div>
                  )}
                </div>

                {/* Review Summary */}
                <div className="co-review" style={{ marginBottom: "1.5rem" }}>
                  <h3 className="co-review__title">Review your order</h3>
                  <div className="co-review__row"><span>Name</span><strong>{name}</strong></div>
                  <div className="co-review__row"><span>Email</span><strong>{email}</strong></div>
                  <div className="co-review__row"><span>Payment via</span><strong>{selectedMethod?.label}</strong></div>
                  <div className="co-review__row co-review__row--total"><span>Total</span><strong>₱{total.toLocaleString()}</strong></div>
                </div>

                <button type="submit" className="btn checkout-submit" disabled={!proofFile}>
                  {proofFile ? "Place Order 🎉" : "Upload Proof to Place Order"}
                </button>
              </div>
            </form>
          )}
        </div>

        {/* ── Right: Order Summary ── */}
        <aside className="checkout-summary">
          <h2 className="checkout-summary__title">Order Summary</h2>
          <div className="checkout-summary__items">
            {cartItems.map((ci) => (
              <div key={ci.product.id} className="checkout-summary__item" style={{ alignItems: "flex-start" }}>
                <div className="checkout-summary__item-visual" style={{ background: ci.product.gradient }}>
                  <span>{ci.product.emoji}</span>
                </div>
                <div className="checkout-summary__item-info" style={{ flex: 1 }}>
                  <p className="checkout-summary__item-name" style={{ margin: 0, fontWeight: 600, fontSize: "0.875rem" }}>{ci.product.name}</p>
                  <p className="checkout-summary__item-cat" style={{ margin: "2px 0 6px 0", fontSize: "0.75rem", color: "var(--color-text-muted)" }}>{ci.product.category}</p>
                  
                  {/* Quantity controls */}
                  <div style={{ display: "flex", alignItems: "center", gap: "0.5rem" }}>
                    <button 
                      type="button"
                      onClick={() => handleUpdateQty(ci.product.id, ci.qty - 1)}
                      style={{
                        width: "20px",
                        height: "20px",
                        borderRadius: "4px",
                        border: "1px solid var(--color-border)",
                        background: "var(--color-white)",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        fontSize: "0.75rem",
                        cursor: "pointer"
                      }}
                    >-</button>
                    <span style={{ fontSize: "0.8125rem", fontWeight: 700, minWidth: "16px", textAlign: "center" }}>{ci.qty}</span>
                    <button 
                      type="button"
                      onClick={() => handleUpdateQty(ci.product.id, ci.qty + 1)}
                      style={{
                        width: "20px",
                        height: "20px",
                        borderRadius: "4px",
                        border: "1px solid var(--color-border)",
                        background: "var(--color-white)",
                        display: "flex",
                        alignItems: "center",
                        justifyContent: "center",
                        fontSize: "0.75rem",
                        cursor: "pointer"
                      }}
                    >+</button>
                  </div>
                </div>
                <div style={{ textAlign: "right", flexShrink: 0 }}>
                  <span className="checkout-summary__item-price" style={{ display: "block", fontWeight: 700 }}>₱{(ci.product.price * ci.qty).toLocaleString()}</span>
                  {ci.qty > 1 && (
                    <span style={{ fontSize: "0.6875rem", color: "var(--color-text-muted)", display: "block" }}>
                      ₱{ci.product.price.toLocaleString()} each
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>
          <div className="checkout-summary__divider" />
          <div className="checkout-summary__row"><span>Subtotal</span><span>₱{total.toLocaleString()}</span></div>
          <div className="checkout-summary__row checkout-summary__row--free"><span>Delivery</span><span>Free — Instant Download</span></div>
          <div className="checkout-summary__divider" />
          <div className="checkout-summary__row checkout-summary__row--total"><span>Total</span><span>₱{total.toLocaleString()}</span></div>
          <div className="checkout-summary__trust">
            <span>🔒 Secure checkout</span>
            <span>⚡ Instant access</span>
          </div>
        </aside>
      </div>
    </div>
  );
}

/* ─── Thank You Page ─────────────────────────────────────────────────────── */
function ThankYouPage({
  orderId, buyer, cartItems, onContinue,
}: {
  orderId: string;
  buyer: { name: string; email: string };
  cartItems: CartItem[];
  onContinue: () => void;
}) {
  const total = cartItems.reduce((s, i) => s + i.product.price * i.qty, 0);
  const date  = new Date().toLocaleDateString("en-PH", { year: "numeric", month: "long", day: "numeric" });

  return (
    <div className="thankyou-page">
      <div className="container thankyou-layout">

        {/* Confetti ring */}
        <div className="thankyou-ring" aria-hidden="true">
          <span className="thankyou-ring__inner"><span>✅</span></span>
        </div>

        <h1 className="thankyou-title">Thank you, {buyer.name.split(" ")[0]}! 🎉</h1>
        <p className="thankyou-sub">Your order has been received. We&rsquo;ll send your download link to <strong>{buyer.email}</strong> within a few minutes.</p>

        {/* Order card */}
        <div className="thankyou-card">
          <div className="thankyou-card__header">
            <div>
              <span className="thankyou-card__label">Order ID</span>
              <span className="thankyou-card__id">{orderId}</span>
            </div>
            <div>
              <span className="thankyou-card__label">Date</span>
              <span className="thankyou-card__date">{date}</span>
            </div>
            <div>
              <span className="thankyou-card__label">Status</span>
              <span className="thankyou-card__status">Processing</span>
            </div>
          </div>

          <div className="thankyou-card__items">
            {cartItems.map((ci) => (
              <div key={ci.product.id} className="thankyou-card__item">
                <div className="thankyou-card__item-visual" style={{ background: ci.product.gradient }}>
                  <span>{ci.product.emoji}</span>
                </div>
                <div className="thankyou-card__item-info">
                  <p className="thankyou-card__item-name">
                    {ci.product.name} {ci.qty > 1 && <span className="checkout-summary__item-qty">×{ci.qty}</span>}
                  </p>
                  <p className="thankyou-card__item-cat">{ci.product.category}</p>
                  <ul className="thankyou-card__item-includes">
                    {ci.product.includes.slice(0, 3).map((inc) => (
                      <li key={inc}>
                        <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M13 4 6 11 3 8"/></svg>
                        {inc}
                      </li>
                    ))}
                    {ci.product.includes.length > 3 && <li className="thankyou-card__item-more">+{ci.product.includes.length - 3} more</li>}
                  </ul>
                </div>
                <div style={{ textAlign: "right", flexShrink: 0 }}>
                  <span className="thankyou-card__item-price" style={{ display: "block", fontWeight: 700 }}>₱{(ci.product.price * ci.qty).toLocaleString()}</span>
                  {ci.qty > 1 && (
                    <span style={{ fontSize: "0.6875rem", color: "var(--color-text-muted)", display: "block" }}>
                      ₱{ci.product.price.toLocaleString()} each
                    </span>
                  )}
                </div>
              </div>
            ))}
          </div>

          <div className="thankyou-card__footer">
            <div className="thankyou-card__footer-row">
              <span>Subtotal</span><span>₱{total.toLocaleString()}</span>
            </div>
            <div className="thankyou-card__footer-row">
              <span>Delivery</span><span className="thankyou-green">Free — Instant Download</span>
            </div>
            <div className="thankyou-card__footer-divider" />
            <div className="thankyou-card__footer-row thankyou-card__footer-row--total">
              <span>Total Paid</span><span>₱{total.toLocaleString()}</span>
            </div>
          </div>
        </div>

        {/* What's next */}
        <div className="thankyou-next">
          <h2 className="thankyou-next__title">What happens next?</h2>
          <div className="thankyou-next__steps">
            {[
              { icon: "🔍", title: "We verify your payment", desc: "Your proof of payment is reviewed — usually within 1–2 hours." },
              { icon: "📧", title: "Download link sent", desc: `A download email will be sent to ${buyer.email}.` },
              { icon: "🚀", title: "Start learning", desc: "Access your materials and start landing clients right away." },
            ].map((s) => (
              <div key={s.title} className="thankyou-next__step">
                <span className="thankyou-next__step-icon">{s.icon}</span>
                <h3>{s.title}</h3>
                <p>{s.desc}</p>
              </div>
            ))}
          </div>
        </div>

        <div className="thankyou-actions">
          <button className="btn thankyou-btn-primary" onClick={onContinue}>
            Continue Shopping
          </button>
          <a href="/#contact" className="btn thankyou-btn-secondary">
            Contact Support
          </a>
        </div>

        <p className="thankyou-footer-note">Questions? Email us at <a href="mailto:hello@shopifyvamadeeasy.com">hello@shopifyvamadeeasy.com</a></p>

      </div>
    </div>
  );
}

/* ─── Main ShopPage ──────────────────────────────────────────────────────── */
function ShopPage() {
  const [activeCategory, setActiveCategory] = useState("All");
  const [cartItems, setCartItems]   = useState<CartItem[]>(() => {
    try {
      const saved = localStorage.getItem("cartItems");
      return saved ? JSON.parse(saved) : [];
    } catch {
      return [];
    }
  });
  const [justAdded, setJustAdded]   = useState<Product | null>(null);
  const [addedId, setAddedId]       = useState<number | null>(null);
  const [view, setView]             = useState<View>("shop");
  const [orderId, setOrderId]       = useState("");
  const [buyer, setBuyer]           = useState<{ name: string; email: string } | null>(null);

  // Sync to localStorage and notify other components
  useEffect(() => {
    try {
      localStorage.setItem("cartItems", JSON.stringify(cartItems));
      window.dispatchEvent(new Event("cart-updated"));
    } catch (e) {
      console.error(e);
    }
  }, [cartItems]);

  // Check URL query parameters for checkout view routing
  useEffect(() => {
    try {
      const params = new URLSearchParams(window.location.search);
      if (params.get("checkout") === "true") {
        setView("checkout");
        // Clean URL parameter so page refresh behaves normally
        window.history.replaceState({}, document.title, window.location.pathname);
      }
    } catch (e) {
      console.error(e);
    }
  }, []);

  const filtered = activeCategory === "All" ? PRODUCTS : PRODUCTS.filter((p) => p.category === activeCategory);
  const cartCount = cartItems.reduce((s, i) => s + i.qty, 0);

  const [scrolled, setScrolled] = useState(false);
  const [navOpen, setNavOpen] = useState(false);
  useEffect(() => {
    const onScroll = () => setScrolled(window.scrollY > 50);
    window.addEventListener("scroll", onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener("scroll", onScroll);
  }, []);

  // Lock body scroll when modal or mobile nav is open
  useEffect(() => {
    document.body.style.overflow = justAdded || navOpen ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [justAdded, navOpen]);

  function addToCart(product: Product) {
    setCartItems((prev) => {
      const existing = prev.find((i) => i.product.id === product.id);
      if (existing) return prev;
      return [...prev, { product, qty: 1 }];
    });
    setAddedId(product.id);
    setTimeout(() => setAddedId(null), 1800);
    setJustAdded(product);
  }

  function handleComplete(oid: string, b: { name: string; email: string }) {
    setOrderId(oid);
    setBuyer(b);
    setView("thankyou");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function handleContinue() {
    setCartItems([]);
    setView("shop");
    window.scrollTo({ top: 0, behavior: "smooth" });
  }

  function handleUpdateQty(productId: number, newQty: number) {
    setCartItems((prev) => {
      if (newQty <= 0) {
        const next = prev.filter((i) => i.product.id !== productId);
        if (next.length === 0) {
          setView("shop");
        }
        return next;
      }
      return prev.map((i) => i.product.id === productId ? { ...i, qty: newQty } : i);
    });
  }

  /* Thank You */
  if (view === "thankyou" && buyer) {
    return (
      <div className="shop-page">
        <ShopHeader cartCount={0} onCartClick={() => {}} scrolled={scrolled} navOpen={navOpen} setNavOpen={setNavOpen} />
        <ThankYouPage orderId={orderId} buyer={buyer} cartItems={cartItems} onContinue={handleContinue} />
        <ShopFooter />
      </div>
    );
  }

  /* Checkout */
  if (view === "checkout") {
    return (
      <div className="shop-page">
        <ShopHeader cartCount={cartCount} onCartClick={() => setView("shop")} scrolled={scrolled} navOpen={navOpen} setNavOpen={setNavOpen} />
        <CheckoutPage cartItems={cartItems} onBack={() => setView("shop")} onComplete={handleComplete} onUpdateQty={handleUpdateQty} />
        <ShopFooter />
      </div>
    );
  }

  /* Shop grid */
  return (
    <div className="shop-page">
      <ShopHeader cartCount={cartCount} onCartClick={() => cartCount > 0 && setView("checkout")} scrolled={scrolled} navOpen={navOpen} setNavOpen={setNavOpen} />

      <main>
        {/* Hero */}
        <section className="shop-hero">
          <div className="shop-hero__bg" aria-hidden="true" />
          <div className="container shop-hero__content">
            <span className="shop-hero__label">Digital Products</span>
            <h1 className="shop-hero__title">Tools that get you <em>hired.</em></h1>
            <p className="shop-hero__sub">Every product is battle-tested by real Shopify VA students.<br />Instant download. Lifetime access. No fluff.</p>
            <div className="shop-hero__trust">
              <span>⚡ Instant access after payment</span>
              <span>🔒 Secure checkout via GCash / PayMongo</span>
              <span>💚 Used by 500+ students</span>
            </div>
          </div>
        </section>

        {/* Filter */}
        <div className="shop-filter">
          <div className="container shop-filter__inner">
            <div className="shop-filter__pills">
              {CATEGORIES.map((c) => (
                <button key={c} type="button"
                  className={`shop-filter__pill ${activeCategory === c ? "shop-filter__pill--active" : ""}`}
                  onClick={() => setActiveCategory(c)}>{c}</button>
              ))}
            </div>
            <p className="shop-filter__count">{filtered.length} product{filtered.length !== 1 ? "s" : ""}</p>
          </div>
        </div>

        {/* Grid */}
        <section className="shop-grid-section">
          <div className="container">
            <div className="shop-grid">
              {filtered.map((p) => (
                <article key={p.id} className="shop-card">
                  <div className="shop-card__visual" style={{ background: p.gradient }}>
                    <span className="shop-card__emoji" aria-hidden="true">{p.emoji}</span>
                    {p.badge && <span className={`shop-card__badge shop-card__badge--${p.badgeColor}`}>{p.badge}</span>}
                    {p.tag  && <span className="shop-card__tag">{p.tag}</span>}
                  </div>
                  <div className="shop-card__body">
                    <div className="shop-card__meta">
                      <span className="shop-card__category">{p.category}</span>
                      <div className="shop-card__rating"><Stars rating={p.rating} /><span className="shop-card__rating-count">({p.reviews})</span></div>
                    </div>
                    <h2 className="shop-card__name">{p.name}</h2>
                    <p className="shop-card__desc">{p.desc}</p>
                    <ul className="shop-card__includes">
                      {p.includes.map((item) => (
                        <li key={item}>
                          <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d="M13 4 6 11 3 8"/></svg>
                          {item}
                        </li>
                      ))}
                    </ul>
                    <div className="shop-card__footer">
                      <div className="shop-card__price-block">
                        <span className="shop-card__price">₱{p.price.toLocaleString()}</span>
                        <span className="shop-card__original">₱{p.original.toLocaleString()}</span>
                        <span className="shop-card__savings-pill">{p.savings}% off</span>
                      </div>
                      <button type="button"
                        className={`btn shop-card__cta ${addedId === p.id ? "shop-card__cta--added" : ""}`}
                        onClick={() => addToCart(p)}>
                        {addedId === p.id ? (<><CheckIcon />Added!</>) : (<><CartIcon size={16} />Add to Cart</>)}
                      </button>
                    </div>
                  </div>
                </article>
              ))}
            </div>
          </div>
        </section>

        {/* Guarantee */}
        <section className="shop-guarantee">
          <div className="container shop-guarantee__inner">
            {[
              { icon: "⚡", title: "Instant Access",   desc: "Download your files immediately after payment." },
              { icon: "🔒", title: "Secure Checkout",  desc: "GCash & PayMongo — trusted by thousands." },
              { icon: "♾️", title: "Lifetime Access",  desc: "Yours forever. No subscriptions, no expiry." },
              { icon: "🎯", title: "Proven Results",   desc: "Students land clients within days of using these tools." },
            ].map((g) => (
              <div key={g.title} className="shop-guarantee__item">
                <span className="shop-guarantee__icon" aria-hidden="true">{g.icon}</span>
                <h3 className="shop-guarantee__title">{g.title}</h3>
                <p className="shop-guarantee__desc">{g.desc}</p>
              </div>
            ))}
          </div>
        </section>
      </main>

      <ShopFooter />

      {/* Cart added modal */}
      {justAdded && (
        <CartModal
          product={justAdded}
          cartCount={cartCount}
          onClose={() => setJustAdded(null)}
          onCheckout={() => { setJustAdded(null); setView("checkout"); window.scrollTo({ top: 0, behavior: "smooth" }); }}
        />
      )}
    </div>
  );
}

const SHOP_NAV_LINKS = [
  { href: "/#home", label: "Home" },
  { href: "/#about", label: "About" },
  { href: "/#pricing", label: "Courses" },
  { href: "/#services", label: "What You'll Learn" },
  { href: "/#process", label: "How It Works" },
  { href: "/#reviews", label: "Testimonials" },
  { href: "/shop", label: "Shop" },
  { href: "/#contact", label: "Contact" },
];

/* ─── Shared Header / Footer ─────────────────────────────────────────────── */
function ShopHeader({
  cartCount,
  onCartClick,
  scrolled,
  navOpen,
  setNavOpen,
}: {
  cartCount: number;
  onCartClick: () => void;
  scrolled: boolean;
  navOpen: boolean;
  setNavOpen: (o: boolean) => void;
}) {
  return (
    <header className={`shop-header ${scrolled ? "shop-header--scrolled" : ""}`}>
      <div className="container shop-header__inner">
        <Link to="/" className="logo" onClick={() => setNavOpen(false)}>
          <img src="/logo.png" alt="Shopify VA Made Easy" className="logo__img" height={46} />
        </Link>
        <nav className={`nav ${navOpen ? "nav--open" : ""}`}>
          {SHOP_NAV_LINKS.map((l) => {
            const isActive = l.href === "/shop";
            if (isActive) {
              return (
                <Link key={l.href} to="/shop" className="nav__link nav__link--active" onClick={() => setNavOpen(false)}>
                  {l.label}
                </Link>
              );
            }
            return (
              <a key={l.href} href={l.href} className="nav__link" onClick={() => setNavOpen(false)}>
                {l.label}
              </a>
            );
          })}
        </nav>
        <div style={{ display: "flex", alignItems: "center", gap: "1rem", pointerEvents: "auto" }}>
          <button className="shop-cart-btn" aria-label={`Cart — ${cartCount} items`} onClick={onCartClick}>
            <CartIcon />
            {cartCount > 0 && <span className="shop-cart-btn__count">{cartCount}</span>}
          </button>
          <button
            type="button"
            className={`nav-toggle ${navOpen ? "nav-toggle--active" : ""}`}
            aria-label="Toggle menu"
            onClick={() => setNavOpen(!navOpen)}
          >
            <span /><span /><span />
          </button>
        </div>
      </div>
    </header>
  );
}

function ShopFooter() {
  return (
    <footer className="shop-footer">
      <div className="container shop-footer__inner">
        <p>© {new Date().getFullYear()} Shopify VA Made Easy — All digital products are delivered instantly.</p>
        <div className="shop-footer__links">
          <Link to="/">Home</Link>
          <a href="/#contact">Contact</a>
          <a href="mailto:hello@shopifyvamadeeasy.com">hello@shopifyvamadeeasy.com</a>
        </div>
      </div>
    </footer>
  );
}
