const heroImage = "/images/hero-factory.jpg";
const vancouverHeroImage = "/images/vancouver-hero.jpg";

const metrics = [
  { label: "Equipment types", value: "5", detail: "single, dual, four-shaft, mills, lines" },
  { label: "Throughput", value: "1-60", detail: "TPH, fully customizable" },
  { label: "Exported to", value: "50+", detail: "countries worldwide" }
];

const applications = [
  {
    title: "Tires & rubber",
    copy: "Shred any tire up to 2000 mm diameter — no pre-processing needed. Steel-belted, radial, or bias-ply."
  },
  {
    title: "MSW & bulky waste",
    copy: "Household waste, furniture, mattresses, appliances. Dual-shaft low-speed design prevents jamming."
  },
  {
    title: "Plastics & e-waste",
    copy: "PET bottles, containers, circuit boards, hard drives, phones. PLC-controlled auto-feed and auto-reverse."
  },
  {
    title: "Industrial & medical",
    copy: "Paint drums, factory scrap, medical waste, expired pharmaceuticals. Custom blade configs for every material."
  },
  {
    title: "Wood & biomass",
    copy: "Pallets, straw, corn stalks, demolition wood. High-torque gearbox handles thick, fibrous material."
  },
  {
    title: "Paper mill & textiles",
    copy: "Plastic film, ropes, leather scraps, fabric, shoes. Anti-wrap cutter design for tangling materials."
  }
];

function Icon({ name, size = 18 }) {
  var ref = React.useRef(null);
  React.useEffect(function() {
    var el = ref.current;
    if (!el || !window.lucide) return;
    // Reset to fresh <i> so lucide can process it
    el.innerHTML = '<i data-lucide="' + name + '" style="width:' + size + 'px;height:' + size + 'px"></i>';
    window.lucide.createIcons({ nodes: el.querySelectorAll("[data-lucide]") });
  }, [name, size]);
  return <span ref={ref} style={{ display: "inline-flex", width: size, height: size }} aria-hidden="true" />;
}

function Breadcrumb({ items }) {
  return (
    <nav className="breadcrumb" aria-label="Breadcrumb">
      {items.map((item, i) => (
        <React.Fragment key={item.label}>
          {i > 0 && <span className="breadcrumb-sep">/</span>}
          {item.href ? (
            <a href={item.href}>{item.label}</a>
          ) : (
            <span className="breadcrumb-current">{item.label}</span>
          )}
        </React.Fragment>
      ))}
    </nav>
  );
}

function Header() {
  const [menuOpen, setMenuOpen] = React.useState(false);

  return (
    <>
      <header className="site-header">
        <a className="brand" href="/" aria-label="Starglow Shredder home">
          <span className="brand-mark">SS</span>
          <span>
            <strong>Starglow Shredder</strong>
            <small>Engineered shredding solutions</small>
          </span>
        </a>
        <nav className="desktop-nav" aria-label="Primary navigation">
          <a href="/products/">Products</a>
          <a href="/#applications">Applications</a>
          <a href="/#process">How It Works</a>
          <a href="#contact">Contact</a>
          <span className="nav-divider" />
          <a href="tel:+16041234567" className="nav-contact"><Icon name="phone" size={14} /> +1 (604) 123-4567</a>
          <a href="mailto:info@starglow-shredder.com" className="nav-contact"><Icon name="mail" size={14} /> info@starglow-shredder.com</a>
        </nav>
        <a className="header-cta" href="#contact">
          Request Quote
          <Icon name="arrow-right" size={16} />
        </a>
        <button className="menu-button" aria-label={menuOpen ? "Close menu" : "Open menu"} onClick={() => setMenuOpen(!menuOpen)}>
          <Icon name={menuOpen ? "x" : "menu"} size={22} />
        </button>
      </header>
      {menuOpen && (
        <nav className="mobile-nav" aria-label="Mobile navigation">
          <a href="/products/" onClick={() => setMenuOpen(false)}>Products</a>
          <a href="/#applications" onClick={() => setMenuOpen(false)}>Applications</a>
          <a href="/#process" onClick={() => setMenuOpen(false)}>How It Works</a>
          <a href="#contact" onClick={() => setMenuOpen(false)}>Contact</a>
          <a className="mobile-nav-cta" href="#contact" onClick={() => setMenuOpen(false)}>
            Request Quote
          </a>
          <a href="tel:+16041234567" onClick={() => setMenuOpen(false)}>
            <Icon name="phone" size={16} /> +1 (604) 123-4567
          </a>
          <a href="mailto:info@starglow-shredder.com" onClick={() => setMenuOpen(false)}>
            <Icon name="mail" size={16} /> info@starglow-shredder.com
          </a>
        </nav>
      )}
    </>
  );
}

function Hero() {
  return (
    <section className="hero" id="top">
      <img
        className="hero-image"
        src={heroImage}
        alt="Industrial shredder processing waste material"
      />
      <div className="hero-overlay" />
      <div className="hero-content">
        <div className="hero-copy">
          <span className="eyebrow">Custom-built shredding equipment</span>
          <h1>Your Material. Your Specs. Your Shredder.</h1>
          <p>
            Low-speed, high-torque shredders for tires, MSW, plastics, e-waste, wood, and industrial scrap. Dual-shaft, single-shaft, or complete lines — each machine built to your material and throughput. Exported to 50+ countries.
          </p>
          <div className="hero-actions">
            <a className="primary-button" href="/products/">
              View equipment
              <Icon name="arrow-right" size={18} />
            </a>
            <a className="secondary-button" href="#contact">
              Request a quote
            </a>
          </div>
        </div>
        <aside className="hero-panel" aria-label="Quote inputs">
          <span>Why our shredders</span>
          <ul>
            <li>HRC 58-62 blades, 8000+ hour life</li>
            <li>PLC auto-control with overload reverse</li>
            <li>Gearbox-driven low-speed high-torque</li>
            <li>Custom blade, shaft, and screen configs</li>
          </ul>
        </aside>
      </div>
    </section>
  );
}

function MetricBand() {
  return (
    <section className="metric-band" aria-label="Template metrics">
      {metrics.map((metric) => (
        <div className="metric" key={metric.label}>
          <strong>{metric.value}</strong>
          <span>{metric.label}</span>
          <small>{metric.detail}</small>
        </div>
      ))}
    </section>
  );
}

function SectionIntro({ eyebrow, title, copy }) {
  return (
    <div className="section-intro">
      <span className="eyebrow">{eyebrow}</span>
      <h2>{title}</h2>
      <p>{copy}</p>
    </div>
  );
}

function ProductCard({ product }) {
  return (
    <a className="product-card" href={`/products/${product.slug}/`}>
      <div className="product-image-wrap">
        <img src={product.image} alt={product.alt} loading="lazy" />
        <span>{product.eyebrow}</span>
      </div>
      <div className="product-content">
        <h3>{product.name}</h3>
        <div className="spec-grid" aria-label={`${product.name} key specifications`}>
          <div>
            <Icon name="gauge" size={18} />
            <span>{product.capacity}</span>
            <small>Capacity</small>
          </div>
          <div>
            <Icon name="ruler" size={18} />
            <span>{product.feedSize}</span>
            <small>Feed size</small>
          </div>
          <div>
            <Icon name="factory" size={18} />
            <span>{product.power}</span>
            <small>Power</small>
          </div>
        </div>
        <div className="tag-row">
          {product.applications.map((application) => (
            <span key={application}>{application}</span>
          ))}
        </div>
        <span className="product-detail-link">
          View details
          <Icon name="arrow-right" size={16} />
        </span>
      </div>
    </a>
  );
}

function ProductsSection({ products }) {
  return (
    <section className="section" id="products">
      <SectionIntro
        eyebrow="Equipment"
        title="Every shredder built to order"
        copy="Single-shaft, double-shaft, four-shaft, hammer mills, or turnkey lines. Pick a base — we customize everything else."
      />
      {products.length ? (
        <div className="product-grid">
          {products.map((product) => (
            <ProductCard product={product} key={product.slug} />
          ))}
        </div>
      ) : (
        <div className="loading-panel">Loading equipment from Node API...</div>
      )}
    </section>
  );
}

function ApplicationsSection() {
  return (
    <section className="section application-section" id="applications">
      <SectionIntro
        eyebrow="Applications"
        title="What do you need to shred?"
        copy="Tires, MSW, plastics, e-waste, wood, medical waste, textiles — we've built machines for all of them."
      />
      <div className="application-grid">
        {applications.map((application, index) => (
          <article className="application-card" key={application.title}>
            <span>0{index + 1}</span>
            <h3>{application.title}</h3>
            <p>{application.copy}</p>
          </article>
        ))}
      </div>
    </section>
  );
}

function ProcessSection() {
  const steps = [
    {
      icon: "search",
      title: "Tell us the material",
      copy: "What you shred, how much, what size output."
    },
    {
      icon: "clipboard-list",
      title: "We configure the machine",
      copy: "Cutters, screens, motor, and layout — all matched to your job."
    },
    {
      icon: "truck",
      title: "Quote in your inbox",
      copy: "Specs, drawing, parts list, and delivered pricing."
    }
  ];

  return (
    <section className="process-section" id="process">
      <SectionIntro
        eyebrow="How it works"
        title="From material spec to custom quote"
        copy="Three steps. No generic catalog machines."
      />
      <div className="process-grid">
        {steps.map((step) => {
          return (
            <article className="process-card" key={step.title}>
              <Icon name={step.icon} size={24} />
              <h3>{step.title}</h3>
              <p>{step.copy}</p>
            </article>
          );
        })}
      </div>
    </section>
  );
}

function ProductTable({ products }) {
  return (
    <section className="section table-section" aria-label="Product model comparison">
      <SectionIntro
        eyebrow="Specs"
        title="Base models — all customizable"
        copy="Starting configurations. Every parameter can be adjusted to your project."
      />
      <div className="table-wrap">
        <table>
          <thead>
            <tr>
              <th>Family</th>
              <th>Model</th>
              <th>Capacity</th>
              <th>Max feed</th>
              <th>Power</th>
            </tr>
          </thead>
          <tbody>
            {products.flatMap((product) =>
              product.models.map((model) => (
                <tr key={`${product.slug}-${model.model}`}>
                  <td>{product.name}</td>
                  <td>{model.model}</td>
                  <td>{model.capacity}</td>
                  <td>{model.feed}</td>
                  <td>{model.motor}</td>
                </tr>
              ))
            )}
          </tbody>
        </table>
      </div>
    </section>
  );
}

const serviceAreas = [
  { region: "Greater Vancouver", cities: "Vancouver, Burnaby, Surrey, Richmond, North Vancouver, West Vancouver, Delta, New Westminster" },
  { region: "Fraser Valley", cities: "Langley, Abbotsford, Chilliwack, Mission, Maple Ridge, Coquitlam, Port Coquitlam" },
  { region: "BC Interior", cities: "Kamloops, Kelowna, Vernon, Penticton, Prince George, Williams Lake" },
  { region: "Vancouver Island", cities: "Victoria, Nanaimo, Courtenay, Campbell River, Duncan" }
];

function ServiceAreasSection() {
  return (
    <section className="section service-areas-section" id="service-areas">
      <SectionIntro
        eyebrow="Delivery"
        title="Direct to your site across BC"
        copy="Factory to job site. Vancouver, Interior, Island — we deliver and commission."
      />
      <div className="service-areas-grid">
        {serviceAreas.map((area) => (
          <article className="service-area-card" key={area.region}>
            <Icon name="map-pin" size={20} />
            <h3>{area.region}</h3>
            <p>{area.cities}</p>
          </article>
        ))}
      </div>
    </section>
  );
}

function VancouverPage({ products }) {
  return (
    <>
      <section className="hero" id="top">
        <img
          className="hero-image"
          src={vancouverHeroImage}
          alt="Industrial shredding equipment for waste processing in Vancouver BC"
        />
        <div className="hero-overlay" />
        <div className="hero-content">
          <div className="hero-copy">
            <span className="eyebrow">Vancouver, BC</span>
            <h1>Shredding Equipment in Vancouver, British Columbia</h1>
            <p>
              Industrial shredders, hammer mills, and complete shredding lines
              for tire recycling, wood waste, rubber, plastics, and municipal solid
              waste in Vancouver and the Greater Vancouver area. Factory-direct with engineering support.
            </p>
            <div className="hero-actions">
              <a className="primary-button" href="/products/">
                View equipment
                <Icon name="arrow-right" size={18} />
              </a>
              <a className="secondary-button" href="#contact">
                Request a quote
              </a>
            </div>
          </div>
          <aside className="hero-panel" aria-label="Vancouver service highlights">
            <span>Why Vancouver chooses us</span>
            <ul>
              <li>Delivery to Lower Mainland sites</li>
              <li>Engineering support for BC projects</li>
              <li>Cutters and spare parts available</li>
              <li>On-site commissioning available</li>
            </ul>
          </aside>
        </div>
      </section>
      <MetricBand />
      <ProductsSection products={products} />
      <ServiceAreasSection />
      <ProcessSection />
    </>
  );
}

function ContactSection() {
  const [status, setStatus] = React.useState("idle");
  const [error, setError] = React.useState("");

  async function handleSubmit(e) {
    e.preventDefault();
    setError("");
    setStatus("sending");

    const form = e.target;
    const data = {
      material: form.material.value.trim(),
      capacity: form.capacity.value.trim(),
      outputSize: form.outputSize.value.trim(),
      email: form.email.value.trim()
    };

    if (!data.material || !data.capacity || !data.outputSize || !data.email) {
      setError("Please fill in all fields.");
      setStatus("idle");
      return;
    }

    try {
      const res = await fetch("/api/rfq", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      const result = await res.json();
      if (!res.ok) {
        setError(result.error || "Something went wrong.");
        setStatus("idle");
        return;
      }
      setStatus("sent");
      form.reset();
    } catch (err) {
      setError("Network error. Please try again.");
      setStatus("idle");
    }
  }

  return (
    <section className="contact-section" id="contact">
      <div>
        <span className="eyebrow">Get started</span>
        <h2>Tell us what you shred. We build it.</h2>
        <p>
          Material, throughput, output size — that's all we need. You get a custom-configured quote with specs, layout, and pricing.
        </p>
        <div className="proof-list">
          <span>
            <Icon name="shield-check" size={18} />
            HRC 58-62 blades, 8000+ hour life
          </span>
          <span>
            <Icon name="download" size={18} />
            Specs, layout drawing, and parts list
          </span>
          <span>
            <Icon name="map-pinned" size={18} />
            Exported to 50+ countries
          </span>
        </div>
      </div>

      {status === "sent" ? (
        <div className="rfq-card rfq-success">
          <Icon name="check-circle-2" size={40} />
          <h3>RFQ submitted</h3>
          <p>We have received your material specs. Our engineering team will reply within one business day.</p>
          <button type="button" onClick={() => setStatus("idle")}>
            Submit another inquiry
          </button>
        </div>
      ) : (
        <form className="rfq-card" onSubmit={handleSubmit}>
          <label>
            Material
            <input name="material" type="text" placeholder="Tires, wood pallets, rubber..." required />
          </label>
          <label>
            Capacity
            <input name="capacity" type="text" placeholder="e.g. 10 TPH" required />
          </label>
          <label>
            Target output size
            <input name="outputSize" type="text" placeholder="e.g. 50 mm chips" required />
          </label>
          <label>
            Work email
            <input name="email" type="email" placeholder="name@company.ca" required />
          </label>
          {error && <p className="rfq-error">{error}</p>}
          <button type="submit" disabled={status === "sending"}>
            <Icon name="mail" size={18} />
            {status === "sending" ? "Sending..." : "Send RFQ"}
          </button>
          <small>
            Your information is used only to prepare a technical quotation.
          </small>
        </form>
      )}
    </section>
  );
}

function SocialIcon({ type, size = 20 }) {
  var paths = {
    facebook: <path d="M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>,
    instagram: <><rect x="2" y="2" width="20" height="20" rx="5" ry="5" fill="none" stroke="currentColor" strokeWidth="2"/><circle cx="12" cy="12" r="4.5" fill="none" stroke="currentColor" strokeWidth="2"/><circle cx="17.5" cy="6.5" r="1.5" fill="currentColor"/></>,
    whatsapp: <><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51l-.57-.01c-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347z" fill="currentColor"/><path d="M12 2C6.477 2 2 6.477 2 12c0 1.89.525 3.66 1.438 5.168L2 22l4.832-1.438A9.955 9.955 0 0 0 12 22c5.523 0 10-4.477 10-10S17.523 2 12 2z" fill="none" stroke="currentColor" strokeWidth="1.5"/></>,
    gmail: <><rect x="2" y="4" width="20" height="16" rx="2" fill="none" stroke="currentColor" strokeWidth="2"/><path d="M22 4L12 13 2 4" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/></>
  };
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" aria-hidden="true">
      {paths[type]}
    </svg>
  );
}

function SocialFloat() {
  return (
    <div className="social-float">
      <a href="https://www.facebook.com/share/18sLxFRejt/?mibextid=wwXIfr" target="_blank" rel="noopener noreferrer" aria-label="Facebook" className="social-float-btn social-fb">
        <SocialIcon type="facebook" size={20} />
      </a>
      <a href="https://www.instagram.com/xuyerayland?igsh=MXF0Zng3d3RyYTRtbQ%3D%3D&utm_source=qr" target="_blank" rel="noopener noreferrer" aria-label="Instagram" className="social-float-btn social-ig">
        <SocialIcon type="instagram" size={20} />
      </a>
      <a href="https://wa.me/8617326128268" target="_blank" rel="noopener noreferrer" aria-label="WhatsApp" className="social-float-btn social-wa">
        <SocialIcon type="whatsapp" size={20} />
      </a>
      <a href="mailto:Zhouq3640@gmail.com" aria-label="Email" className="social-float-btn social-gm">
        <SocialIcon type="gmail" size={20} />
      </a>
    </div>
  );
}

function Footer() {
  return (
    <footer className="footer">
      <div>
        <strong>Starglow Shredder</strong>
        <p>Custom-built industrial shredders exported to 50+ countries. Low-speed high-torque dual-shaft, single-shaft, and four-shaft machines for tires, MSW, plastics, e-waste, wood, and industrial scrap.</p>
      </div>
      <nav aria-label="Footer navigation">
        <a href="tel:+16041234567">
          <Icon name="phone" size={16} />
          +1 (604) 123-4567
        </a>
        <a href="mailto:Zhouq3640@gmail.com">
          <Icon name="mail" size={16} />
          Zhouq3640@gmail.com
        </a>
        <a href="/products/">
          <Icon name="check-circle-2" size={16} />
          Products
        </a>
        <a href="#contact">
          <Icon name="check-circle-2" size={16} />
          Request Quote
        </a>
      </nav>
      <div className="footer-social" aria-label="Social media">
        <a href="https://www.facebook.com/share/18sLxFRejt/?mibextid=wwXIfr" target="_blank" rel="noopener noreferrer" aria-label="Facebook">
          <SocialIcon type="facebook" size={18} />
        </a>
        <a href="https://www.instagram.com/xuyerayland?igsh=MXF0Zng3d3RyYTRtbQ%3D%3D&utm_source=qr" target="_blank" rel="noopener noreferrer" aria-label="Instagram">
          <SocialIcon type="instagram" size={18} />
        </a>
        <a href="https://wa.me/8617326128268" target="_blank" rel="noopener noreferrer" aria-label="WhatsApp">
          <SocialIcon type="whatsapp" size={18} />
        </a>
        <a href="mailto:Zhouq3640@gmail.com" aria-label="Email">
          <SocialIcon type="gmail" size={18} />
        </a>
      </div>
    </footer>
  );
}

// --- Page components ---

function ProductsListPage({ products }) {
  return (
    <section className="section" style={{ paddingTop: 48 }}>
      <Breadcrumb items={[
        { label: "Home", href: "/" },
        { label: "Products" }
      ]} />
      <SectionIntro
        eyebrow="Equipment"
        title="Shredding Equipment for Sale in Canada"
        copy="Compare single-shaft, double-shaft, and four-shaft shredders, hammer mills, and complete shredding lines for tire, wood, rubber, and waste recycling projects."
      />
      {products.length ? (
        <div className="product-grid">
          {products.map((product) => (
            <ProductCard product={product} key={product.slug} />
          ))}
        </div>
      ) : (
        <div className="loading-panel">Loading equipment...</div>
      )}
    </section>
  );
}

function ProductDetailPage({ product, allProducts }) {
  const [activeTab, setActiveTab] = React.useState("overview");
  const [selectedModel, setSelectedModel] = React.useState(null);
  const [imageZoomed, setImageZoomed] = React.useState(false);
  const [quoteStatus, setQuoteStatus] = React.useState("idle");
  const [quoteError, setQuoteError] = React.useState("");

  const relatedProducts = (allProducts || []).filter((p) => p.slug !== product.slug);

  const tabs = [
    { id: "overview", label: "Overview", icon: "layout-dashboard" },
    { id: "models", label: "Models", icon: "layers" },
    { id: "quote", label: "Get Quote", icon: "mail" }
  ];

  React.useEffect(() => {
    setActiveTab("overview");
    setSelectedModel(null);
    setImageZoomed(false);
    setQuoteStatus("idle");
    setQuoteError("");
  }, [product.slug]);


  async function handleDetailQuote(e) {
    e.preventDefault();
    setQuoteError("");
    setQuoteStatus("sending");
    const form = e.target;
    const data = {
      material: form.material.value.trim(),
      capacity: form.capacity.value.trim(),
      outputSize: form.outputSize.value.trim(),
      email: form.email.value.trim()
    };
    if (!data.material || !data.capacity || !data.outputSize || !data.email) {
      setQuoteError("Please fill in all fields.");
      setQuoteStatus("idle");
      return;
    }
    try {
      const res = await fetch("/api/rfq", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      const result = await res.json();
      if (!res.ok) {
        setQuoteError(result.error || "Something went wrong.");
        setQuoteStatus("idle");
        return;
      }
      setQuoteStatus("sent");
      form.reset();
    } catch (err) {
      setQuoteError("Network error. Please try again.");
      setQuoteStatus("idle");
    }
  }

  return (
    <section className="section" style={{ paddingTop: 48 }}>
      <Breadcrumb items={[
        { label: "Home", href: "/" },
        { label: "Products", href: "/products/" },
        { label: product.name }
      ]} />

      {/* Hero area */}
      <div className="pd-hero">
        <div className="pd-hero-info">
          <span className="eyebrow">{product.eyebrow}</span>
          <h1>{product.name}</h1>
          <p className="pd-summary">{product.summary}</p>
          <div className="pd-specs-row">
            <div className="pd-spec-chip">
              <Icon name="gauge" size={16} />
              <div>
                <small>Capacity</small>
                <strong>{product.capacity}</strong>
              </div>
            </div>
            <div className="pd-spec-chip">
              <Icon name="ruler" size={16} />
              <div>
                <small>Feed size</small>
                <strong>{product.feedSize}</strong>
              </div>
            </div>
            <div className="pd-spec-chip">
              <Icon name="factory" size={16} />
              <div>
                <small>Power</small>
                <strong>{product.power}</strong>
              </div>
            </div>
          </div>
          <div className="tag-row">
            {product.applications.map((app) => (
              <span key={app}>{app}</span>
            ))}
          </div>
          <p className="fit-note">{product.fit}</p>
        </div>
        <div
          className={"pd-image-container" + (imageZoomed ? " zoomed" : "")}
          onClick={() => setImageZoomed(!imageZoomed)}
          title={imageZoomed ? "Click to zoom out" : "Click to zoom in"}
        >
          <img src={product.image} alt={product.alt} />
          <span className="pd-zoom-hint">
            <Icon name={imageZoomed ? "zoom-out" : "zoom-in"} size={16} />
            {imageZoomed ? "Zoom out" : "Zoom in"}
          </span>
        </div>
      </div>

      {/* Tab bar */}
      <div className="pd-tabs">
        {tabs.map((tab) => (
          <button
            key={tab.id}
            className={"pd-tab" + (activeTab === tab.id ? " active" : "")}
            onClick={() => setActiveTab(tab.id)}
          >
            <Icon name={tab.icon} size={16} />
            {tab.label}
          </button>
        ))}
      </div>

      {/* Tab content */}
      <div className="pd-tab-content">
        {activeTab === "overview" && (
          <div className="pd-overview">
            <div className="pd-feature-grid">
              <div className="pd-feature-card">
                <div className="pd-feature-icon">
                  <Icon name="shield-check" size={22} />
                </div>
                <h3>HRC 58-62 hardened blades</h3>
                <p>55SiCr / H13 tool steel, vacuum quenched and cryogenically treated. 3-5x wear life vs standard blades, 8000+ hours continuous use.</p>
              </div>
              <div className="pd-feature-card">
                <div className="pd-feature-icon">
                  <Icon name="settings" size={22} />
                </div>
                <h3>PLC auto-control</h3>
                <p>Start, stop, reverse, and overload auto-reverse. Dual-shaft independent drive with auto-feed. Anti-wrap cutter design prevents jamming.</p>
              </div>
              <div className="pd-feature-card">
                <div className="pd-feature-icon">
                  <Icon name="zap" size={22} />
                </div>
                <h3>Low speed, high torque</h3>
                <p>Gearbox-driven low RPM operation delivers massive cutting force with low noise and minimal dust. Built for 24/7 heavy-duty use.</p>
              </div>
              <div className="pd-feature-card">
                <div className="pd-feature-icon">
                  <Icon name="wrench" size={22} />
                </div>
                <h3>Easy blade service</h3>
                <p>Removable blade seats with 4 cutting edges per blade — rotate 90° when worn. Welded box with post-weld annealing for rigidity.</p>
              </div>
            </div>

            <div className="pd-overview-table">
              <h3>All models at a glance</h3>
              <div className="table-wrap">
                <table>
                  <thead>
                    <tr>
                      <th>Model</th>
                      <th>Capacity</th>
                      <th>Max Feed</th>
                      <th>Motor Power</th>
                    </tr>
                  </thead>
                  <tbody>
                    {product.models.map((m) => (
                      <tr
                        key={m.model}
                        className={selectedModel === m.model ? "row-selected" : ""}
                        onClick={() => setSelectedModel(selectedModel === m.model ? null : m.model)}
                        style={{ cursor: "pointer" }}
                      >
                        <td><strong>{m.model}</strong></td>
                        <td>{m.capacity}</td>
                        <td>{m.feed}</td>
                        <td>{m.motor}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>

            <div className="pd-cta-banner">
              <div>
                <h3>Ready to get a quote for {product.name}?</h3>
                <p>Send your project parameters and our team will configure the right model for your material.</p>
              </div>
              <button className="primary-button" onClick={() => setActiveTab("quote")}>
                Get Quote
                <Icon name="arrow-right" size={16} />
              </button>
            </div>
          </div>
        )}

        {activeTab === "models" && (
          <div className="pd-models">
            <p className="pd-models-hint">Select a model to see detailed specifications</p>
            <div className="pd-model-cards">
              {product.models.map((m) => (
                <div
                  key={m.model}
                  className={"pd-model-card" + (selectedModel === m.model ? " selected" : "")}
                  onClick={() => setSelectedModel(selectedModel === m.model ? null : m.model)}
                >
                  <div className="pd-model-header">
                    <span className="pd-model-name">{m.model}</span>
                    <span className="pd-model-badge">
                      {selectedModel === m.model ? "Selected" : "Select"}
                    </span>
                  </div>
                  <div className="pd-model-specs">
                    <div>
                      <Icon name="gauge" size={15} />
                      <small>Capacity</small>
                      <span>{m.capacity}</span>
                    </div>
                    <div>
                      <Icon name="ruler" size={15} />
                      <small>Max Feed</small>
                      <span>{m.feed}</span>
                    </div>
                    <div>
                      <Icon name="zap" size={15} />
                      <small>Motor</small>
                      <span>{m.motor}</span>
                    </div>
                  </div>
                  {selectedModel === m.model && (
                    <div className="pd-model-detail">
                      <p>This model handles {m.capacity} throughput with a max feed size of {m.feed}, powered by a {m.motor} motor.</p>
                      <button className="primary-button" onClick={(e) => { e.stopPropagation(); setActiveTab("quote"); }}>
                        Quote this model
                        <Icon name="arrow-right" size={16} />
                      </button>
                    </div>
                  )}
                </div>
              ))}
            </div>

            <div className="pd-compare-section">
              <h3>Model comparison</h3>
              <div className="table-wrap">
                <table>
                  <thead>
                    <tr>
                      <th>Model</th>
                      <th>Capacity</th>
                      <th>Max Feed</th>
                      <th>Motor Power</th>
                    </tr>
                  </thead>
                  <tbody>
                    {product.models.map((m) => (
                      <tr
                        key={m.model}
                        className={selectedModel === m.model ? "row-selected" : ""}
                        onClick={() => setSelectedModel(selectedModel === m.model ? null : m.model)}
                        style={{ cursor: "pointer" }}
                      >
                        <td><strong>{m.model}</strong></td>
                        <td>{m.capacity}</td>
                        <td>{m.feed}</td>
                        <td>{m.motor}</td>
                      </tr>
                    ))}
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        )}

        {activeTab === "quote" && (
          <div className="pd-quote-tab">
            {quoteStatus === "sent" ? (
              <div className="pd-quote-success">
                <Icon name="check-circle-2" size={48} />
                <h3>Quote request submitted</h3>
                <p>We have received your parameters for <strong>{product.name}</strong>{selectedModel ? ` (${selectedModel})` : ""}. Our engineering team will reply within one business day.</p>
                <button className="secondary-button" onClick={() => setQuoteStatus("idle")} style={{ border: "1px solid var(--line)", color: "var(--primary-dark)" }}>
                  Submit another inquiry
                </button>
              </div>
            ) : (
              <div className="pd-quote-layout">
                <div className="pd-quote-info">
                  <h3>Request a quote for {product.name}</h3>
                  {selectedModel && (
                    <div className="pd-quote-selected-model">
                      <Icon name="check-circle-2" size={16} />
                      <span>Selected model: <strong>{selectedModel}</strong></span>
                      <button onClick={() => setSelectedModel(null)}>
                        <Icon name="x" size={14} />
                      </button>
                    </div>
                  )}
                  <p>Fill in your project parameters below. Our team will configure the equipment and return a quote with specs, layout, and delivered pricing.</p>
                  <div className="pd-quote-includes">
                    <h4>Your quote will include:</h4>
                    <ul>
                      <li><Icon name="check" size={14} /> Sized equipment recommendation</li>
                      <li><Icon name="check" size={14} /> Capacity and performance data</li>
                      <li><Icon name="check" size={14} /> General arrangement drawing</li>
                      <li><Icon name="check" size={14} /> Delivered pricing to your site</li>
                    </ul>
                  </div>
                </div>
                <form className="pd-quote-form" onSubmit={handleDetailQuote}>
                  <label>
                    Material type
                    <input name="material" type="text" placeholder="Tires, wood pallets, rubber..." required />
                  </label>
                  <label>
                    Required capacity
                    <input name="capacity" type="text" placeholder="e.g. 10 TPH" required />
                  </label>
                  <label>
                    Target output size
                    <input name="outputSize" type="text" placeholder="e.g. 50 mm chips" required />
                  </label>
                  <label>
                    Work email
                    <input name="email" type="email" placeholder="name@company.ca" required />
                  </label>
                  {quoteError && <p className="rfq-error">{quoteError}</p>}
                  <button type="submit" disabled={quoteStatus === "sending"}>
                    <Icon name="send" size={16} />
                    {quoteStatus === "sending" ? "Sending..." : "Submit Quote Request"}
                  </button>
                  <small>Your information is used only to prepare a technical quotation.</small>
                </form>
              </div>
            )}
          </div>
        )}
      </div>

      {/* Related products */}
      {relatedProducts.length > 0 && (
        <div className="pd-related">
          <h3>Related equipment</h3>
          <div className="pd-related-grid">
            {relatedProducts.map((rp) => (
              <a key={rp.slug} href={`/products/${rp.slug}/`} className="pd-related-card">
                <div className="pd-related-image">
                  <img src={rp.image} alt={rp.alt} loading="lazy" />
                </div>
                <div className="pd-related-info">
                  <span className="eyebrow">{rp.eyebrow}</span>
                  <h4>{rp.name}</h4>
                  <span className="pd-related-spec">{rp.capacity}</span>
                </div>
              </a>
            ))}
          </div>
        </div>
      )}
    </section>
  );
}

// --- App with routing ---

function App() {
  const [products, setProducts] = React.useState([]);
  const path = window.location.pathname;

  React.useEffect(() => {
    fetch("/api/products")
      .then((response) => response.json())
      .then(setProducts)
      .catch(() => setProducts([]));
  }, []);

  // Product detail page
  const slugMatch = path.match(/^\/products\/([a-z0-9-]+)\/?$/);
  if (slugMatch) {
    const slug = slugMatch[1];
    const product = products.find((p) => p.slug === slug);
    return (
      <>
        <Header />
        <main>
          {product ? (
            <ProductDetailPage product={product} allProducts={products} />
          ) : products.length > 0 ? (
            <section className="section" style={{ paddingTop: 48 }}>
              <div className="loading-panel">Product not found.</div>
            </section>
          ) : (
            <section className="section" style={{ paddingTop: 48 }}>
              <div className="loading-panel">Loading...</div>
            </section>
          )}
          <ContactSection />
        </main>
        <Footer />
        <SocialFloat />
      </>
    );
  }

  // Products listing page
  if (path === "/products" || path === "/products/") {
    return (
      <>
        <Header />
        <main>
          <ProductsListPage products={products} />
          <ContactSection />
        </main>
        <Footer />
        <SocialFloat />
      </>
    );
  }

  // Vancouver landing page
  if (path === "/vancouver" || path === "/vancouver/") {
    return (
      <>
        <Header />
        <main>
          <VancouverPage products={products} />
          <ContactSection />
        </main>
        <Footer />
        <SocialFloat />
      </>
    );
  }

  // Homepage
  return (
    <>
      <Header />
      <main>
        <Hero />
        <ProductsSection products={products} />
        <ProcessSection />
        <ContactSection />
      </main>
      <Footer />
      <SocialFloat />
    </>
  );
}

window.App = App;
