const { useMemo, useState, useEffect } = React;

const { company, categories } = window.LP_SITE_DATA;
const products = window.LP_SITE_DATA.products.map((product) => ({
  ...product,
  purity: product.category === "Accessories" ? "Sterile supply" : "NLT 99%",
  moq: company.orderMinimum,
  lead: company.leadTime,
  coa: product.category !== "Accessories",
}));

const nav = [
  ["Home", "#/"],
  ["Products", "#/products"],
  ["Custom Synthesis", "#/custom-synthesis"],
  ["Quality / COA", "#/quality"],
  ["Wholesale", "#/wholesale"],
  ["Quote", "#/quote"],
  ["Contact", "#/contact"],
];

function useRoute() {
  const [hash, setHash] = useState(location.hash || "#/");
  useEffect(() => {
    const onHash = () => setHash(location.hash || "#/");
    addEventListener("hashchange", onHash);
    return () => removeEventListener("hashchange", onHash);
  }, []);
  return hash.replace(/^#/, "");
}

function useInquiry() {
  const [items, setItems] = useState(() => JSON.parse(localStorage.getItem("lpInquiry") || "[]"));
  const [notice, setNotice] = useState("");
  useEffect(() => localStorage.setItem("lpInquiry", JSON.stringify(items)), [items]);
  useEffect(() => {
    if (!notice) return;
    const timer = setTimeout(() => setNotice(""), 2800);
    return () => clearTimeout(timer);
  }, [notice]);
  const add = (product, note = "") => {
    setNotice(note ? `${product.code}: COA request added` : `${product.code}: added to Inquiry List`);
    setItems((current) => {
      if (current.some((item) => item.slug === product.slug && item.note === note)) return current;
      return [...current, { slug: product.slug, code: product.code, name: product.name, spec: product.spec, note }];
    });
  };
  const remove = (slug) => setItems((current) => current.filter((item) => item.slug !== slug));
  const clear = () => setItems([]);
  return { items, add, remove, clear, notice };
}

function App() {
  const route = useRoute();
  const inquiry = useInquiry();
  const productMatch = route.match(/^\/products\/(.+)$/);
  const product = productMatch ? products.find((item) => item.slug === productMatch[1]) : null;

  return (
    <>
      <Header count={inquiry.items.length} />
      <main>
        {route === "/" && <Home inquiry={inquiry} />}
        {route === "/products" && <ProductsPage inquiry={inquiry} />}
        {product && <ProductDetail product={product} inquiry={inquiry} />}
        {route === "/quote" && <QuotePage inquiry={inquiry} />}
        {route === "/custom-synthesis" && <CustomSynthesis />}
        {route === "/quality" && <Quality />}
        {route === "/wholesale" && <Wholesale />}
        {route === "/contact" && <Contact />}
        {!["/", "/products", "/quote", "/custom-synthesis", "/quality", "/wholesale", "/contact"].includes(route) && !product && <NotFound />}
      </main>
      <Footer />
      <FloatingInquiry count={inquiry.items.length} />
      {inquiry.notice && <div className="toast" role="status">{inquiry.notice}</div>}
    </>
  );
}

function Header({ count }) {
  const [open, setOpen] = useState(false);
  return (
    <header className="site-header">
      <a className="brand" href="#/">
        <img src="./assets/lp-peptide-logo.jpg" alt="LP Peptide Labs logo" />
        <span>LP Peptide Labs</span>
      </a>
      <button className="nav-toggle" aria-label="Open navigation" aria-expanded={open} onClick={() => setOpen(!open)}>Menu</button>
      <nav className={open ? "open" : ""}>
        {nav.map(([label, href]) => <a key={href} href={href} onClick={() => setOpen(false)}>{label}</a>)}
        <a className="nav-quote" href="#/quote">Inquiry List ({count})</a>
      </nav>
    </header>
  );
}

function Home({ inquiry }) {
  return (
    <>
      <section className="hero">
        <div className="hero-copy">
          <p className="eyebrow">Professional peptide manufacturer</p>
          <h1>Factory-backed peptide supply for serious research brands</h1>
          <p className="hero-text">
            LP Peptide Labs helps U.S.-market distributors, research buyers and private label partners source documented peptide batches with quote-based pricing, COA support and 8-13 day U.S. fulfillment.
          </p>
          <div className="trust-row">
            <span>HPLC/MS documentation</span>
            <span>Batch traceability</span>
            <span>Wholesale inventory</span>
            <span>Private label programs</span>
          </div>
          <div className="hero-actions">
            <a className="btn primary" href="#/quote">Request Wholesale Quote</a>
            <a className="btn secondary" href="#/products">View Product Database</a>
          </div>
        </div>
        <div className="hero-panel">
          <img src="./assets/real-product-assortment.png" alt="LP Peptide Labs packaged research peptide assortment" />
          <div className="lab-console">
            <div><span>Batch status</span><strong>COA ready</strong></div>
            <div><span>Testing</span><strong>HPLC / MS</strong></div>
            <div><span>Supply mode</span><strong>B2B quote</strong></div>
          </div>
          <div className="metric-grid">
            <div><strong>$299</strong><span>Total order minimum incl. shipping & service</span></div>
            <div><strong>8-13d</strong><span>Typical U.S. fulfillment</span></div>
            <div><strong>COA</strong><span>Available for qualified buyers</span></div>
            <div><strong>$5k+</strong><span>Private label programs</span></div>
          </div>
        </div>
      </section>
      <section className="procurement-strip" aria-label="Procurement highlights">
        <div><span>Catalog purity</span><strong>NLT 99%</strong></div>
        <div><span>Mixed-order minimum</span><strong>$299 total</strong></div>
        <div><span>Typical U.S. lead time</span><strong>8-13 days</strong></div>
        <div><span>Documentation</span><strong>COA on request</strong></div>
      </section>
      <section className="section">
        <div className="section-head">
          <p className="eyebrow">Supplier system</p>
          <h2>Built for serious B2B peptide sourcing</h2>
        </div>
        <div className="feature-grid">
          {[
            ["Product database", "A searchable catalog organized for sourcing teams, resellers and repeat wholesale buyers."],
            ["Quote-first sales", "Wholesale pricing stays private while the site captures high-intent RFQ demand."],
            ["COA trust center", "Sample documentation, HPLC/MS language and latest-batch COA request flows."],
            ["Private label ready", "Custom label and packaging support for qualified bulk orders around $5,000+."],
          ].map(([title, body]) => <InfoCard key={title} title={title} body={body} />)}
        </div>
      </section>
      <ProductStrip inquiry={inquiry} />
      <CtaBand />
    </>
  );
}

function ProductStrip({ inquiry }) {
  return (
    <section className="section muted">
      <div className="section-head inline">
        <div>
          <p className="eyebrow">High-demand categories</p>
          <h2>Core products for wholesale inquiry</h2>
        </div>
        <a className="text-link" href="#/products">Browse all products</a>
      </div>
      <div className="product-grid">
        {products.slice(0, 6).map((product) => <ProductCard key={product.slug} product={product} inquiry={inquiry} />)}
      </div>
    </section>
  );
}

function ProductsPage({ inquiry }) {
  const [query, setQuery] = useState("");
  const [category, setCategory] = useState("All");
  const filtered = useMemo(() => products.filter((product) => {
    const matchesCategory = category === "All" || product.category === category;
    const text = `${product.name} ${product.code} ${product.spec} ${product.category}`.toLowerCase();
    return matchesCategory && text.includes(query.toLowerCase());
  }), [query, category]);

  return (
    <>
      <PageHero title="Product Database" eyebrow="COA-supported catalog" body="Search by product name, short code, specification or research category. Add items to an inquiry list and request a wholesale quote." />
      <section className="section">
        <div className="catalog-layout">
          <aside className="catalog-sidebar">
            <p className="eyebrow">Categories</p>
            <button className={category === "All" ? "active" : ""} onClick={() => setCategory("All")}>All products</button>
            {categories.map((item) => <button key={item} className={category === item ? "active" : ""} onClick={() => setCategory(item)}>{item}</button>)}
          </aside>
          <div>
            <div className="filters">
              <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search products, codes or specs..." />
              <select value={category} onChange={(e) => setCategory(e.target.value)}>
                <option>All</option>
                {categories.map((item) => <option key={item}>{item}</option>)}
              </select>
            </div>
            <div className="catalog-status">
              <strong>{filtered.length} products</strong>
              <span>{inquiry.items.length} items in inquiry list</span>
            </div>
            <div className="product-grid">
              {filtered.map((product) => <ProductCard key={product.slug} product={product} inquiry={inquiry} />)}
            </div>
          </div>
          <InquiryPanel inquiry={inquiry} />
        </div>
      </section>
    </>
  );
}

function ProductCard({ product, inquiry }) {
  return (
    <article className="product-card">
      <a className="product-image" href={`#/products/${product.slug}`}>
        {product.image ? (
          <img src={product.image} alt={`${product.code} ${product.name} research peptide product presentation`} />
        ) : (
          <span className="product-image-missing">
            <strong>{product.code}-LP</strong>
            <small>{product.spec.replace(" x ", " / ")}</small>
            <em>Product image pending</em>
          </span>
        )}
      </a>
      <div className="product-top">
        <span className="code">{product.code}</span>
        <span className={product.coa ? "badge good" : "badge"}>{product.coa ? "COA available" : "Docs on request"}</span>
      </div>
      <h3><a href={`#/products/${product.slug}`}>{product.name}</a></h3>
      <p>{product.highlight}</p>
      <dl>
        <div><dt>Spec</dt><dd>{product.spec}</dd></div>
        <div><dt>Purity</dt><dd>{product.purity}</dd></div>
        <div><dt>Order minimum</dt><dd>{product.moq}</dd></div>
        <div><dt>Lead time</dt><dd>{product.lead}</dd></div>
      </dl>
      <div className="card-actions">
        <button onClick={() => inquiry.add(product)}>Add to Inquiry List</button>
        <button className="ghost" onClick={() => inquiry.add(product, "COA requested")}>Ask for COA</button>
      </div>
    </article>
  );
}

function ProductDetail({ product, inquiry }) {
  const related = products.filter((item) => item.category === product.category && item.slug !== product.slug).slice(0, 3);
  return (
    <>
      <PageHero title={product.name} eyebrow={`${product.code} - ${product.category}`} body={product.highlight} />
      <section className="section detail-layout">
        <div className="detail-main">
          <h2>Product overview</h2>
          <p>
            {product.name} is listed for qualified B2B research buyers and wholesale partners. LP Peptide Labs provides quote-based supply, batch documentation support and direct fulfillment for approved inquiries.
          </p>
          <div className="spec-table">
            {[
              ["Product code", product.code],
              ["Specification", product.spec],
              ["Purity", product.purity],
              ["Testing", product.coa ? "HPLC / MS documentation available" : "Documentation on request"],
              ["Batch traceability", "Product code, batch number and report date"],
              ["Storage", "Cool, dry, protected from light"],
              ["Order minimum", product.moq],
              ["Typical U.S. lead time", product.lead],
              ["COA status", product.coa ? "Available upon request" : "Documentation on request"],
              ["Use statement", "For research use only. Not for human or animal consumption."],
            ].map(([label, value]) => <div key={label}><span>{label}</span><strong>{value}</strong></div>)}
          </div>
          <div className="doc-panel">
            <div>
              <p className="eyebrow">Documentation</p>
              <h3>COA Available for qualified inquiry</h3>
              <p>Ask for the latest batch report before confirming volume, packaging and shipment details.</p>
            </div>
            <button className="btn primary" onClick={() => inquiry.add(product, "COA requested")}>Ask for COA</button>
          </div>
          {related.length > 0 && (
            <>
              <h2>Related products</h2>
              <div className="related-grid">
                {related.map((item) => <ProductCard key={item.slug} product={item} inquiry={inquiry} />)}
              </div>
            </>
          )}
        </div>
        <aside className="quote-box">
          <h3>Request this product</h3>
          <p>Add this item to your inquiry list or request the latest batch COA before order confirmation.</p>
          <button className="btn full primary" onClick={() => inquiry.add(product)}>Add to Inquiry List</button>
          <button className="btn full secondary" onClick={() => inquiry.add(product, "COA requested")}>Ask for COA</button>
          <a className="btn full outline" href="#/quote">Go to Quote Form</a>
        </aside>
      </section>
    </>
  );
}

function QuotePage({ inquiry }) {
  const [sent, setSent] = useState(false);
  const inquiryText = inquiry.items.map((item) => `${item.code} - ${item.name} (${item.spec})${item.note ? ` - ${item.note}` : ""}`).join("\n");
  const mailto = `mailto:${company.email}?subject=${encodeURIComponent("Wholesale Quote Request")}&body=${encodeURIComponent(inquiryText || "Please send me the wholesale price list.")}`;
  const submitQuote = (event) => {
    event.preventDefault();
    const data = Object.fromEntries(new FormData(event.currentTarget));
    const body = [
      `Name: ${data.name}`,
      `Company: ${data.company || "Not provided"}`,
      `Email: ${data.email}`,
      `Country: ${data.country}`,
      `WhatsApp / Telegram: ${data.messaging || "Not provided"}`,
      `Buyer type: ${data.buyerType}`,
      `Expected order size: ${data.orderSize}`,
      `Preferred contact: ${data.preferredContact}`,
      `Latest COA required: ${data.latestCoa ? "Yes" : "No"}`,
      `Private label / custom packaging: ${data.privateLabel ? "Yes" : "No"}`,
      `Bulk price list requested: ${data.bulkPriceList ? "Yes" : "No"}`,
      "",
      "Products requested:",
      data.products || inquiryText || "Price list requested",
      "",
      `Message: ${data.message || "No additional message"}`,
    ].join("\n");
    setSent(true);
    location.href = `mailto:${company.email}?subject=${encodeURIComponent("Wholesale Quote Request")}&body=${encodeURIComponent(body)}`;
  };
  return (
    <>
      <PageHero title="Request Quote" eyebrow="Fast B2B response" body="Send your product list, quantity and preferred contact channel. Any mixed product order can ship once the total order reaches $299 including shipping and service fee." />
      <section className="section quote-layout">
        <div className="inquiry-list">
          <h2>Inquiry List</h2>
          {inquiry.items.length === 0 ? <p>No products added yet. Browse the product database to build a quote list.</p> : inquiry.items.map((item) => (
            <div className="inquiry-item" key={`${item.slug}-${item.note}`}>
              <div><strong>{item.code}</strong><span>{item.name} - {item.spec}{item.note ? ` - ${item.note}` : ""}</span></div>
              <button onClick={() => inquiry.remove(item.slug)}>Remove</button>
            </div>
          ))}
          <div className="quick-actions">
            {company.whatsapp && <a className="btn secondary" href={`https://wa.me/${company.whatsapp}`} target="_blank">Chat on WhatsApp</a>}
            <a className="btn outline" href={mailto}>Email Quote List</a>
            <button className="btn outline" onClick={inquiry.clear}>Clear List</button>
          </div>
        </div>
        <form className="quote-form" onSubmit={submitQuote}>
          <h2>Buyer details</h2>
          <div className="form-grid">
            <label>Full name<input name="name" required placeholder="Your name" /></label>
            <label>Company / channel<input name="company" placeholder="Distributor, reseller, lab, clinic, brand..." /></label>
            <label>Email<input name="email" required type="email" placeholder="name@company.com" /></label>
            <label>WhatsApp / Telegram<input name="messaging" placeholder="+1... or @username" /></label>
            <label>Destination country<input name="country" required defaultValue="United States" /></label>
            <label>Buyer type<select name="buyerType" defaultValue="Wholesale buyer"><option>Wholesale buyer</option><option>Private label brand</option><option>Research organization</option><option>Reseller / distributor</option></select></label>
            <label>Expected order size<select name="orderSize" defaultValue="$299-$1,000"><option>$299-$1,000</option><option>$1,000-$5,000</option><option>$5,000+ private label</option><option>Recurring monthly supply</option></select></label>
            <label>Preferred contact<select name="preferredContact" defaultValue="Email"><option>WhatsApp</option><option>Telegram</option><option>Email</option></select></label>
          </div>
          <label>Products and quantity<textarea name="products" rows="5" defaultValue={inquiryText} placeholder="Product list, strength, vials and quantity" /></label>
          <div className="option-row">
            <label><input name="latestCoa" type="checkbox" /> Latest COA required</label>
            <label><input name="privateLabel" type="checkbox" /> Private label / custom packaging</label>
            <label><input name="bulkPriceList" type="checkbox" /> Bulk price list requested</label>
          </div>
          <label>Message<textarea name="message" rows="4" placeholder="Target delivery date, packaging request, batch documentation, reorder plan..." /></label>
          <button className="btn primary full">Submit Quote Request</button>
          {sent && <div className="thank-you" role="status"><strong>Thank you.</strong><span>Your email application has opened with the complete quote request. Send it to finish your inquiry.</span></div>}
        </form>
      </section>
    </>
  );
}

function CustomSynthesis() {
  return (
    <>
      <PageHero title="Custom Peptide Synthesis" eyebrow="Qualified bulk programs" body="Support for custom sequences, private label packaging and distributor-ready peptide supply programs." />
      <section className="section split">
        <div>
          <h2>From sequence to packaged supply</h2>
          <p className="section-copy">LP Peptide Labs can support qualified buyers with custom peptide synthesis, packaging coordination, label programs and recurring wholesale supply planning.</p>
          <ul className="check-list">
            <li>Custom sequence review and feasibility check</li>
            <li>Bulk production planning for qualified orders</li>
            <li>Private label and packaging support around $5,000+ programs</li>
            <li>Batch documentation and COA support</li>
          </ul>
        </div>
        <Process />
      </section>
    </>
  );
}

function Quality() {
  return (
    <>
      <PageHero title="Quality & COA Center" eyebrow="Documentation-driven trust" body="COA, HPLC, MS and batch documentation support are central to LP Peptide Labs' B2B sourcing workflow." />
      <section className="section split">
        <div>
          <p className="eyebrow">Testing workflow</p>
          <h2>From batch release to buyer confidence</h2>
          <p className="section-copy">The Quality / COA page is designed to make documentation part of the sales process: buyers can understand what is tested, how batches are identified and how to request the latest report before purchase.</p>
        </div>
        <Process steps={["Batch production record", "HPLC purity review", "MS identity confirmation", "COA release for RFQ"]} />
      </section>
      <section className="section quality-grid">
        {[
          ["COA availability", "Latest batch COA can be requested before order confirmation for qualified wholesale buyers."],
          ["HPLC purity", "Sample reports can include purity, assay, water content and related substances where available."],
          ["MS confirmation", "Mass spectrum identity checks can be shown as part of the documentation package."],
          ["Batch traceability", "Products can be tracked by product code, batch number, manufacture date and report date."],
          ["RUO compliance", "Products are for research use only and not intended for human or animal consumption."],
        ].map(([title, body]) => <InfoCard key={title} title={title} body={body} />)}
      </section>
      <section className="section muted">
        <div className="coa-preview">
          <div>
            <p className="eyebrow">Sample COA module</p>
            <h2>Make COA a conversion asset</h2>
            <p>Instead of publishing every full report publicly, the MVP can show sample COA previews and direct buyers to request latest batch documents by WhatsApp, Telegram or email.</p>
          </div>
          <div className="sample-coa">
            <span>Certificate of Analysis</span>
            <strong>Selank Powder</strong>
            <dl>
              <div><dt>Batch</dt><dd>26010501-01</dd></div>
              <div><dt>Method</dt><dd>HPLC / MS</dd></div>
              <div><dt>Purity</dt><dd>99.8%</dd></div>
              <div><dt>Use</dt><dd>R&D only</dd></div>
            </dl>
          </div>
          <a className="btn primary" href="#/quote">Request Latest COA</a>
        </div>
      </section>
    </>
  );
}

function Wholesale() {
  return (
    <>
      <PageHero title="Bulk & Wholesale Supply" eyebrow="Distributor-ready peptide sourcing" body="Designed for U.S.-market resellers, wholesale buyers, private label programs and repeat catalog replenishment." />
      <section className="section split">
        <div>
          <h2>Wholesale program highlights</h2>
          <ul className="check-list">
            <li>Any mixed product order can ship once the total order reaches $299 including shipping and service fee</li>
            <li>Factory-backed bulk inventory across core peptide categories</li>
            <li>Typical U.S. fulfillment window: 8-13 days</li>
            <li>Private label support for qualified $5,000+ programs</li>
            <li>WhatsApp, Telegram and email support for fast buyer communication</li>
          </ul>
        </div>
        <div className="tier-box">
          <h3>Buyer segments</h3>
          <p><strong>Starter buyers:</strong> catalog quote and $299+ total order minimum.</p>
          <p><strong>Resellers:</strong> recurring wholesale supply and price list access.</p>
          <p><strong>Private label:</strong> custom label and packaging program review.</p>
        </div>
      </section>
    </>
  );
}

function Contact() {
  return (
    <>
      <PageHero title="Contact LP Peptide Labs" eyebrow="B2B inquiry channels" body="Use WhatsApp for fast quotes, Telegram for ongoing sourcing and email for formal purchase inquiries." />
      <section className="section contact-grid">
        <ContactCard title="WhatsApp" value="+852 9791 3717" href={`https://wa.me/${company.whatsapp}`} body="Best for product list, quantity, latest price and stock confirmation." />
        <ContactCard title="Telegram" value="@xiaoxin1978" href={`https://t.me/${company.telegram}`} body="Useful for repeat buyer updates, catalog discussions and availability checks." />
        <ContactCard title="Email" value={company.email} href={`mailto:${company.email}`} body="Recommended for COA requests, formal RFQs, private label and bulk planning." />
      </section>
      <section className="section muted">
        <div className="contact-cta">
          <h2>Send a product list and receive a B2B quote.</h2>
          <p>Include product code, strength, quantity, destination country and whether you need COA or private label packaging.</p>
          <a className="btn primary" href="#/quote">Start Request Quote</a>
        </div>
      </section>
    </>
  );
}

function Process({ steps = ["Submit sequence / target", "Confirm feasibility & order minimum", "Quote production & packaging", "Approve COA & fulfillment"] }) {
  return (
    <div className="process">
      {steps.map((step, idx) => (
        <div key={step}><span>{idx + 1}</span><strong>{step}</strong></div>
      ))}
    </div>
  );
}

function InfoCard({ title, body }) {
  return <article className="info-card"><h3>{title}</h3><p>{body}</p></article>;
}

function ContactCard({ title, value, body, href }) {
  return <article className="contact-card"><span>{title}</span><h3>{value}</h3><p>{body}</p><a href={href} target={href.startsWith("http") ? "_blank" : undefined}>Contact via {title}</a></article>;
}

function InquiryPanel({ inquiry }) {
  return (
    <aside className="inquiry-panel">
      <p className="eyebrow">Inquiry List</p>
      <h3>{inquiry.items.length} selected</h3>
      {inquiry.items.length === 0 ? <p>Add products to build a quote request.</p> : inquiry.items.slice(0, 5).map((item) => (
        <div className="mini-item" key={`${item.slug}-${item.note}`}>
          <strong>{item.code}</strong>
          <span>{item.name}</span>
        </div>
      ))}
      <a className="btn primary full" href="#/quote">Request Quote</a>
    </aside>
  );
}

function PageHero({ eyebrow, title, body }) {
  return <section className="page-hero"><p className="eyebrow">{eyebrow}</p><h1>{title}</h1><p>{body}</p></section>;
}

function CtaBand() {
  return (
    <section className="cta-band">
      <div>
        <p className="eyebrow">Ready for sourcing?</p>
        <h2>Build a quote list and request wholesale terms.</h2>
      </div>
      <a className="btn primary" href="#/quote">Request Quote</a>
    </section>
  );
}

function FloatingInquiry({ count }) {
  return <a className="floating" href="#/quote">Inquiry List <strong>{count}</strong></a>;
}

function NotFound() {
  return <PageHero title="Page not found" eyebrow="404" body="The requested MVP route does not exist." />;
}

function Footer() {
  return (
    <footer>
      <div>
        <strong>LP Peptide Labs</strong>
        <p>Professional peptide supplier for wholesale and private label research-use programs.</p>
      </div>
      <p className="disclaimer">For research use only. Not for human or animal consumption. Information on this MVP is for B2B inquiry and catalog presentation only.</p>
    </footer>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
