import Head from 'next/head';
import Link from 'next/link';

import ProductCard from '../components/ProductCard';
import SiteLayout from '../components/SiteLayout';
import { buildMediaUrl, fetchProducts } from '../lib/api';

const SAMPLE_PRODUCTS = [
  {
    id: null,
    slug: 'sprouted-heritage-loaf',
    name: 'Sprouted Heritage Loaf',
    short_description: 'Organic, freshly milled grains with a caramelized crust and pillowy crumb.',
    price: 12,
    inventory_quantity: 8,
    max_per_order: 2,
    allergens: 'Contains: Wheat, Dairy',
    imageUrl:
      'https://images.unsplash.com/photo-1608198093002-ad4e005484ec?auto=format&fit=crop&w=1200&q=80',
    isSample: true,
  },
  {
    id: null,
    slug: 'malted-maple-bagels',
    name: 'Malted Maple Bagels',
    short_description: 'Slow-fermented bagels with malted barley glaze and maple butter finish.',
    price: 18,
    inventory_quantity: 12,
    max_per_order: 3,
    allergens: 'Contains: Wheat',
    imageUrl:
      'https://images.unsplash.com/photo-1589367920476-0be109c12e82?auto=format&fit=crop&w=1200&q=80',
    isSample: true,
  },
  {
    id: null,
    slug: 'moonbeam-cookie-flight',
    name: 'Moonbeam Cookie Flight',
    short_description: 'Rotating selection of award-winning cookies in seasonal flavors.',
    price: 16,
    inventory_quantity: 15,
    max_per_order: 4,
    allergens: 'Contains: Wheat, Eggs, Dairy',
    imageUrl:
      'https://images.unsplash.com/photo-1499636136210-6f4ee915583e?auto=format&fit=crop&w=1200&q=80',
    isSample: true,
  },
];

const FAQS = [
  {
    question: 'Do you offer gluten free or vegan baked goods?',
    answer:
      'At this time, we do not offer any gluten free baked goods. Some items are naturally vegan friendly. If you have any dietary or allergy concerns, please reach out before placing an order.',
  },
  {
    question: 'Where do you deliver to?',
    answer:
      'We currently deliver to Eau Claire and Altoona, Wisconsin. Need an out-of-area drop-off? Use the secret friend code and I’ll reach out personally to coordinate.',
  },
  {
    question: 'What whole grains do you use in your fresh milled flour?',
    answer:
      'Our exact proportions are proprietary, but we regularly mill the following grains:\n- Hard Red Wheat Berries (varying varietals)\n- Soft Red Wheat Berries (varying varietals)\n- Buckwheat\n\nAnd we are always experimenting with other grains and blends. NOTE: If you have a dietary or allergy concern, please reach out before placing an order.',
  },
  {
    question: 'What are sprouted grains, and why should I eat them?',
    answer:
      'Sprouted grains are whole grains that are allowed to just begin sprouting before they are dehydrated and milled. When a grain sprouts, natural enzymes break down starches and proteins, unlocking flavor and nutrition. Sprouted grain flours are often easier to digest, lower on the glycemic index, and richer in vitamins, minerals, and antioxidants than unsprouted flour.',
  },
  {
    question: "What's a CSB?",
    answer:
      'A Community Supported Bakery share works just like a CSA—pre-purchase 4–8 weeks of weekly boxes and receive breads, bagels, and sweets on a set schedule.',
  },
];

function normalizeProducts(products = []) {
  if (!products.length) {
    return SAMPLE_PRODUCTS;
  }

  return products.map((product) => ({
    ...product,
    imageUrl: buildMediaUrl(product.hero_image) || SAMPLE_PRODUCTS[0].imageUrl,
    isSample: false,
  }));
}

export default function Home({ products }) {
  const displayProducts = normalizeProducts(products);
  const featuredProducts = displayProducts.filter((product) => product.is_featured).slice(0, 3);
  const highlight = featuredProducts.length ? featuredProducts : displayProducts.slice(0, 3);

  return (
    <SiteLayout>
      <Head>
        <title>Full Moon Bakehouse · Eau Claire Microbakery</title>
        <meta
          name="description"
          content="Sprouted grain breads, laminated pastries, and microbatch sweets crafted by Bonna Moon in Eau Claire, WI."
        />
      </Head>

      <div className="wrapper">
        <section className="hero">
          <div>
            <h1>Sprouted grain breads & sweets baked under the Full Moon.</h1>
            <p>
              From award-winning cookies to laminated croissants, every bake starts with organic
              midwest grains sprouted and milled in-house. Reserve your favorites for pickup or
              delivery in Eau Claire and Altoona.
            </p>
            <div className="hero-cta">
              <Link className="btn btn-primary" href="/products">
                Browse products
              </Link>
              <Link className="btn btn-outline" href="/cart">
                View cart & checkout
              </Link>
            </div>
          </div>
          <aside className="product-detail__gallery">
            <h3>How it works</h3>
            <p>
              Preorders open Saturday morning and close Monday afternoon. Choose a pickup window on
              Thursday evening or add $5 contactless delivery within Eau Claire and Altoona on
              Thursday or Friday afternoon.
            </p>
            <div className="product-detail__meta">
              <span>• Pickup: Thursday evening (15 minute windows)</span>
              <span>• Delivery: Thu or Fri · Eau Claire & Altoona ($5)</span>
              <span>• Preorder window: Sat morning → Mon afternoon</span>
            </div>
          </aside>
        </section>
      </div>

      <section className="section">
        <div className="wrapper">
          <div className="section-header">
            <div>
              <h2>Fresh from the bakehouse</h2>
              <p>
                Small-batch menus rotate weekly. These highlights rotate in and out depending on the
                season and the grains that inspire us.
              </p>
            </div>
            <Link className="btn btn-outline" href="/products">
              See all offerings
            </Link>
          </div>

              <div className="product-grid">
                {highlight.map((product) => (
                  <ProductCard key={product.slug || product.name} product={product} />
                ))}
              </div>
        </div>
      </section>

      <section className="section">
        <div className="wrapper">
          <div className="section-header">
            <div>
              <h2>How to order</h2>
              <p>Pick the flow that fits your schedule right now or join the CSB launch list.</p>
            </div>
          </div>

          <div className="product-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(320px, 1fr))' }}>
            <article className="product-card">
              <h3>Option 1 · Weekly preorders</h3>
              <p>
                Pre-orders open Saturday morning and close Monday afternoon each week. Pickups happen
                Thursday evening in 15 minute windows (address provided after purchase). Delivery is
                available within Eau Claire & Altoona on Thursday or Friday afternoon for $5.
              </p>
              <div className="product-card__actions">
                <Link className="btn btn-primary" href="/products">
                  Shop this week&apos;s menu
                </Link>
              </div>
            </article>

            <article className="product-card">
              <h3>Option 2 · CSB boxes</h3>
              <p>
                Community Supported Bakery (CSB) shares are coming soon. Each weekly box includes a
                bread (loaf, pita, focaccia), a pack of bagels or English muffins, and a sweet treat.
                Pricing operates on a sliding scale—pay a little more if you can to feed more
                families.
              </p>
              <div className="product-card__actions">
                <a
                  className="btn btn-outline"
                  href="https://www.fullmoonbakehouse.com/#newsletter"
                  target="_blank"
                  rel="noreferrer"
                >
                  Join the email list
                </a>
              </div>
            </article>
          </div>
        </div>
      </section>

      <section className="section" id="about">
        <div className="wrapper">
          <div className="section-header">
            <div>
              <h2>Meet Bonna Moon</h2>
              <p>Scratch baker, ceramicist, and late-night laminator.</p>
            </div>
          </div>

          <article className="product-card" style={{ gridTemplateColumns: '1fr', gap: '1rem' }}>
            <p>
              I&apos;m Bonna Moon—part-time baker, part-time artist working in ceramics, wood, and metal.
              Full Moon Bakehouse is the microbakery I run from my Eau Claire kitchen, built on a
              decade of dough experiments, award-winning cookies, and a deep love for sprouted
              grains.
            </p>
            <p>
              We sprout and mill our grains in-house, source ingredients with care, and craft every
              bake to be something I&apos;d be proud to feed to my own family. Join the email list for
              preorder reminders, seasonal menus, and CSB launches.
            </p>
          </article>
        </div>
      </section>

      <section className="section" id="faq">
        <div className="wrapper">
          <div className="section-header">
            <div>
              <h2>FAQ</h2>
              <p>Your top questions about ingredients, deliveries, and the CSB shares.</p>
            </div>
          </div>

          <div className="product-grid" style={{ gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))' }}>
            {FAQS.map((item) => (
              <article key={item.question} className="product-card">
                <h3>{item.question}</h3>
                <p style={{ whiteSpace: 'pre-line' }}>{item.answer}</p>
              </article>
            ))}
          </div>
        </div>
      </section>
    </SiteLayout>
  );
}

export async function getServerSideProps() {
  try {
    const products = await fetchProducts();
    return { props: { products } };
  } catch (error) {
    console.warn('Home page data fallback', error);
    return { props: { products: [] } };
  }
}
