/* global React, MARKETS, VENDORS, IN_SEASON, FAQS, OCMap, ApplyForm, SectionHead, getNextMarket, LogoMark, CalIcon */
// All page sections — Hero, Schedule, Map, In Season, Vendors, Apply, About+FAQ, Gallery, Footer.

const { useState: _u3, useEffect: _e3, useMemo: _m3 } = React;

/* -------------------- Hero with next-market banner -------------------- */
function Hero() {
  const [nm, setNm] = _u3(() => window.getNextMarket());
  _e3(() => {
    const id = setInterval(() => setNm(window.getNextMarket()), 60000);
    return () => clearInterval(id);
  }, []);
  const m = nm.market;
  const whenLabel =
    nm.when === "today"    ? "Today" :
    nm.when === "tomorrow" ? "Tomorrow" :
    `${m.day}`;

  return (
    <section id="top" style={{ paddingTop: 56, paddingBottom: 0 }}>
      <div className="wrap">
        <div className="eyebrow" style={{ marginBottom: 22 }}>
          Est. 1989 · Family-run · Four markets a week
        </div>
        <h1 className="display" style={{
          fontSize: "clamp(56px, 11vw, 168px)",
          margin: 0,
          color: "var(--ink)",
        }}>
          Fresh from local farms<br/>
          <span style={{ color: "var(--terracotta)" }}>to Orange County families.</span>
        </h1>

        <div style={{
          display: "grid",
          gridTemplateColumns: "1.4fr 1fr",
          gap: 48,
          marginTop: 56,
          alignItems: "end",
        }}>
          <p className="lede" style={{ maxWidth: "52ch", margin: 0 }}>
            Four mornings a week, in four corners of Orange County, our farmers,
            bakers, and makers set up tents at sunrise. Come buy what was
            picked yesterday, and leave knowing the person who grew it.
          </p>

          {/* Next-market banner */}
          <a href={`#${m.id}`} style={{ textDecoration: "none" }}>
            <div className="card" style={{
              background: "var(--ink)",
              color: "var(--cream-warm)",
              borderColor: "var(--ink)",
              padding: "24px 28px",
              position: "relative",
              overflow: "hidden",
            }}>
              <div style={{
                display: "flex", alignItems: "center", gap: 16,
                marginBottom: 14,
              }}>
                <CalIcon day={m.day.slice(0,3).toUpperCase()}/>
                <div>
                  <div className="eyebrow" style={{ color: "var(--brown-l)" }}>
                    {nm.when === "today" ? "Open right now" :
                     nm.when === "tomorrow" ? "Up next — tomorrow" :
                     `Up next — in ${nm.daysUntil} days`}
                  </div>
                  <div className="display" style={{
                    fontSize: 36, color: "var(--cream-warm)",
                    marginTop: 2,
                  }}>
                    {whenLabel}, see you in {m.name}.
                  </div>
                </div>
              </div>
              <div style={{
                fontFamily: "var(--ui)", fontSize: 13, opacity: 0.78,
                lineHeight: 1.55,
              }}>
                {m.address}<br/>
                {m.hours} · rain or shine
              </div>
              <span style={{
                position: "absolute", right: 24, top: 24,
                fontFamily: "var(--display)", fontStyle: "italic",
                fontSize: 56, color: "var(--terracotta)", opacity: 0.55,
              }}>→</span>
            </div>
          </a>
        </div>

        <div style={{ display: "flex", gap: 12, marginTop: 36, flexWrap: "wrap" }}>
          <a href="#map" className="btn">Find a market near you</a>
          <a href="#apply" className="btn btn-ghost">Become a vendor</a>
        </div>

        {/* Atmospheric photo band — aerial of a market in full swing */}
        <figure style={{
          margin: "72px 0 0",
          position: "relative",
          overflow: "hidden",
          borderRadius: 4,
          aspectRatio: "21 / 9",
          background: "var(--bg-2)",
        }}>
          <img
            src="img/aerial-market.png"
            alt="Aerial view of a busy farmers market with rows of white tents and shoppers"
            style={{
              width: "100%", height: "100%", objectFit: "cover",
              filter: "sepia(0.14) saturate(0.94) contrast(1.04)",
            }}
          />
          <figcaption style={{
            position: "absolute", left: 24, bottom: 20,
            fontFamily: "var(--display)", fontStyle: "italic",
            fontSize: 26, color: "var(--cream-warm)",
            textShadow: "0 1px 14px rgba(0,0,0,0.45)",
          }}>
            Saturday morning, Irvine.
          </figcaption>
        </figure>
      </div>
    </section>
  );
}

/* -------------------- Schedule grid -------------------- */
function Schedule() {
  return (
    <section id="markets">
      <div className="wrap">
        <SectionHead
          eyebrow="Four markets, four mornings"
          title={<>The week <em>at a glance.</em></>}
          lede="Each market has its own personality — its regulars, its specialty vendors, its parking situation. Here's where to be when."
        />
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(4, 1fr)",
          gap: 1,
          background: "var(--rule)",
          border: "1px solid var(--rule)",
        }}>
          {window.MARKETS.map((m) => (
            <article key={m.id} id={m.id}
              style={{
                background: "var(--paper)",
                padding: "32px 28px",
                display: "flex", flexDirection: "column", gap: 14,
                minHeight: 380,
              }}>
              <div style={{
                display: "flex", alignItems: "baseline", justifyContent: "space-between",
                gap: 12,
              }}>
                <div className="eyebrow" style={{ color: m.color }}>{m.day}</div>
                <div className="tiny" style={{ color: "var(--ink-soft)" }}>{m.hours}</div>
              </div>
              <h3 className="display" style={{
                fontSize: 56, margin: 0, color: "var(--ink)",
              }}>{m.name}</h3>
              <p style={{ margin: 0, fontSize: 15, lineHeight: 1.55 }}>{m.blurb}</p>
              <div style={{
                marginTop: "auto", paddingTop: 16,
                borderTop: "1px solid var(--rule)",
                fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink-soft)",
              }}>
                <div style={{ marginBottom: 4 }}>{m.address}</div>
                <div>{m.city}</div>
                <a
                  href={`https://www.google.com/maps/search/?api=1&query=${m.mapsQuery}`}
                  target="_blank" rel="noopener"
                  style={{
                    display: "inline-flex", alignItems: "center", gap: 4,
                    marginTop: 12,
                    color: m.color, textDecoration: "none", fontWeight: 600,
                    borderBottom: "1px solid currentColor", paddingBottom: 1,
                  }}
                >
                  Open in maps →
                </a>
              </div>
            </article>
          ))}
        </div>
        <p className="muted" style={{ marginTop: 18, fontSize: 13, fontStyle: "italic" }}>
          *Severe-weather closures announced on Instagram and our newsletter the morning of.
        </p>
      </div>
    </section>
  );
}

/* -------------------- Map section -------------------- */
function MapSection() {
  const [sel, setSel] = _u3(null);
  const m = sel ? window.MARKETS.find((x) => x.id === sel) : null;
  return (
    <section id="map" style={{ background: "var(--bg-2)" }}>
      <div className="wrap">
        <SectionHead
          eyebrow="Find us"
          title={<>One county, <em>four pins.</em></>}
          lede="Click any pin to see directions. Most of our shoppers travel 10 minutes or less to reach their nearest market — there's almost certainly one near you."
        />
        <div style={{ display: "grid", gridTemplateColumns: "2fr 1fr", gap: 28 }}>
          <OCMap selected={sel} onSelect={setSel}/>
          <aside className="card" style={{ minHeight: 360 }}>
            {m ? (
              <div>
                <div className="eyebrow" style={{ color: m.color, marginBottom: 8 }}>
                  {m.day}s · {m.hours}
                </div>
                <h3 className="display" style={{ fontSize: 48, margin: "0 0 12px" }}>
                  {m.name}
                </h3>
                <p style={{ margin: "0 0 18px", lineHeight: 1.55 }}>{m.blurb}</p>
                <div style={{ fontFamily: "var(--ui)", fontSize: 14, color: "var(--ink-soft)" }}>
                  <div>{m.address}</div>
                  <div>{m.city}</div>
                </div>
                <div style={{ display: "flex", gap: 10, marginTop: 20, flexWrap: "wrap" }}>
                  <a className="btn" href={`https://www.google.com/maps/search/?api=1&query=${m.mapsQuery}`} target="_blank" rel="noopener">
                    Google Maps
                  </a>
                  <a className="btn btn-ghost" href={`http://maps.apple.com/?q=${m.mapsQuery}`} target="_blank" rel="noopener">
                    Apple Maps
                  </a>
                </div>
              </div>
            ) : (
              <div style={{ color: "var(--ink-soft)" }}>
                <div className="eyebrow" style={{ marginBottom: 12 }}>
                  Pick a pin
                </div>
                <p className="lede" style={{ margin: 0, fontSize: 22 }}>
                  Tap a market on the map to see hours, address, and directions.
                </p>
                <div style={{
                  marginTop: 28, paddingTop: 20,
                  borderTop: "1px solid var(--rule)",
                  fontFamily: "var(--ui)", fontSize: 13,
                  color: "var(--ink-soft)",
                }}>
                  <div style={{ marginBottom: 6 }}>· Free parking at three of four markets</div>
                  <div style={{ marginBottom: 6 }}>· EBT &amp; Market Match accepted everywhere</div>
                  <div>· Service dogs always welcome</div>
                </div>
              </div>
            )}
          </aside>
        </div>
      </div>
    </section>
  );
}

/* -------------------- In Season -------------------- */
function InSeason() {
  const months = window.MONTHS;
  const [mi, setMi] = _u3(() => new Date().getMonth());
  _e3(() => {
    // Re-check every hour so the page rolls over month boundaries on its own.
    const id = setInterval(() => setMi(new Date().getMonth()), 3600000);
    return () => clearInterval(id);
  }, []);
  const month = months[mi];
  const isCurrent = mi === new Date().getMonth();
  return (
    <section id="in-season">
      <div className="wrap">
        <SectionHead
          eyebrow={`${month.name} at the market`}
          title={<>What's <em>peaking</em> {isCurrent ? "right now" : `in ${month.name}`}.</>}
          lede="Seasonality is the whole point. Each month, our growers swap their tables to whatever's at its best — here's what to expect, all year."
        />

        {/* Month picker — calendar of months, current month highlighted */}
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(12, 1fr)",
          gap: 4,
          marginBottom: 32,
          fontFamily: "var(--ui)",
          fontSize: 12,
          fontWeight: 600,
          letterSpacing: "0.1em",
          textTransform: "uppercase",
        }}>
          {months.map((m, i) => {
            const today = new Date().getMonth() === i;
            const sel = mi === i;
            return (
              <button key={i}
                onClick={() => setMi(i)}
                style={{
                  padding: "10px 4px",
                  border: "1px solid var(--rule)",
                  background: sel ? "var(--ink)" : (today ? "var(--cream-warm)" : "var(--paper)"),
                  color: sel ? "var(--cream-warm)" : "var(--ink)",
                  cursor: "pointer",
                  position: "relative",
                  borderColor: sel ? "var(--ink)" : "var(--rule)",
                  fontFamily: "inherit",
                  fontWeight: "inherit",
                  letterSpacing: "inherit",
                  textTransform: "inherit",
                  fontSize: "inherit",
                  transition: "background .15s",
                }}>
                {m.name.slice(0,3)}
                {today && <span style={{
                  position: "absolute", top: 4, right: 6,
                  width: 5, height: 5, borderRadius: "50%",
                  background: sel ? "var(--terracotta)" : "var(--terracotta)",
                }}/>}
              </button>
            );
          })}
        </div>

        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(5, 1fr)",
          gap: 1,
          background: "var(--rule)",
          border: "1px solid var(--rule)",
        }}>
          {month.items.slice(0, 10).map((p, i) => (
            <div key={`${month.name}-${i}-${p.name}`} style={{
              background: "var(--paper)",
              padding: 24,
              display: "flex", flexDirection: "column", alignItems: "center",
              gap: 14, textAlign: "center",
            }}>
              <svg width="80" height="80" viewBox="0 0 64 64">
                {window.PRODUCE_GLYPH[p.glyph]}
              </svg>
              <div className="display" style={{
                fontSize: 24, color: "var(--ink)", lineHeight: 1.05,
              }}>{p.name}</div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* -------------------- Vendor list (placeholder) -------------------- */
function Vendors() {
  const [filter, setFilter] = _u3("all");
  const filtered = filter === "all"
    ? window.VENDORS
    : window.VENDORS.filter((v) => v.markets.includes(filter));
  return (
    <section id="vendors" style={{ background: "var(--bg-2)" }}>
      <div className="wrap">
        <SectionHead
          eyebrow="A small sample"
          title={<>The folks <em>behind the tents.</em></>}
          lede="Over a hundred vendors rotate through our four markets. Below is a partial list — we're working on a complete searchable directory. Coming soon."
        />
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 24 }}>
          <button
            className={"checkpill" + (filter === "all" ? " is-on" : "")}
            onClick={() => setFilter("all")}
            style={{ border: "1px solid var(--rule)" }}
          >
            <span className="dot"/>All markets
          </button>
          {window.MARKETS.map((m) => (
            <button key={m.id}
              className={"checkpill" + (filter === m.id ? " is-on" : "")}
              onClick={() => setFilter(m.id)}>
              <span className="dot"/>{m.name}
            </button>
          ))}
        </div>
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(280px, 1fr))",
          gap: 1,
          background: "var(--rule)",
          border: "1px solid var(--rule)",
        }}>
          {filtered.map((v) => (
            <article key={v.name} style={{
              background: "var(--paper)",
              padding: "24px 22px",
              display: "flex", flexDirection: "column", gap: 8,
              minHeight: 160,
            }}>
              <div className="tiny" style={{ color: "var(--brown)" }}>{v.category}</div>
              <h4 className="display" style={{
                fontSize: 30, margin: 0, lineHeight: 1.05,
              }}>{v.name}</h4>
              <div style={{ fontSize: 14, color: "var(--ink-soft)" }}>
                from {v.from}
              </div>
              <div style={{
                marginTop: "auto", paddingTop: 12,
                display: "flex", flexWrap: "wrap", gap: 6,
              }}>
                {v.markets.map((id) => {
                  const mk = window.MARKETS.find((x) => x.id === id);
                  return (
                    <span key={id} style={{
                      fontFamily: "var(--ui)",
                      fontSize: 11,
                      letterSpacing: "0.08em",
                      textTransform: "uppercase",
                      padding: "3px 8px",
                      border: `1px solid ${mk.color}`,
                      color: mk.color,
                      borderRadius: 999,
                    }}>{mk.day.slice(0,3)}</span>
                  );
                })}
              </div>
            </article>
          ))}
        </div>
        <p className="muted" style={{ marginTop: 18, fontSize: 13, fontStyle: "italic" }}>
          A full searchable vendor directory is coming. Want to be on it? <a href="#apply" style={{ color: "var(--terracotta)" }}>Apply to vend.</a>
        </p>
      </div>
    </section>
  );
}

/* -------------------- Apply section wrapper -------------------- */
function Apply() {
  return (
    <section id="apply">
      <div className="wrap">
        <SectionHead
          eyebrow="For farmers, bakers & makers"
          title={<>Apply to <em>vend.</em></>}
          lede="We accept new vendors year-round. Tell us a little about what you grow or make and which markets you'd like to join — we read every application personally."
        />
        <ApplyForm/>
      </div>
    </section>
  );
}

/* -------------------- About + FAQ -------------------- */
function About() {
  const [open, setOpen] = _u3(0);
  return (
    <section id="about" style={{ background: "var(--ink)", color: "var(--cream-warm)" }}>
      <div className="wrap">
        <div style={{
          display: "grid",
          gridTemplateColumns: "1fr 1.2fr",
          gap: 64,
          alignItems: "start",
        }}>
          <div>
            <div className="eyebrow" style={{ color: "var(--brown-l)", marginBottom: 18 }}>
              Our story
            </div>
            <h2 className="display" style={{
              fontSize: "clamp(48px, 6vw, 88px)",
              margin: 0, color: "var(--cream-warm)",
              lineHeight: 0.96,
            }}>
              A family business,<br/>
              <em style={{ color: "var(--terracotta)" }}>three generations in.</em>
            </h2>
            <p className="lede" style={{ color: "var(--cream-warm)", opacity: 0.85, marginTop: 28 }}>
              We started in 1989 with a single Saturday market in a church
              parking lot and 14 farms. Almost forty years later, four mornings
              a week, we still do it the same way: certified producers only, no
              resellers, no middlemen.
            </p>
            <p style={{ opacity: 0.78, lineHeight: 1.6, marginTop: 16 }}>
              Every farmer at our markets grew or made what they're selling.
              Every dollar you spend stays within an hour's drive of where you
              live. That's the whole idea.
            </p>
          </div>

          <div>
            <div className="eyebrow" style={{ color: "var(--brown-l)", marginBottom: 18 }}>
              Common questions
            </div>
            <div>
              {window.FAQS.map((f, i) => (
                <div key={i} style={{
                  borderTop: "1px solid rgba(255,255,255,0.12)",
                  borderBottom: i === window.FAQS.length - 1 ? "1px solid rgba(255,255,255,0.12)" : "none",
                }}>
                  <button
                    onClick={() => setOpen(open === i ? -1 : i)}
                    style={{
                      width: "100%", textAlign: "left",
                      background: "transparent", border: "none",
                      color: "var(--cream-warm)",
                      padding: "20px 0",
                      display: "flex", justifyContent: "space-between", alignItems: "center",
                      gap: 16,
                      fontFamily: "var(--display)",
                      fontStyle: "italic",
                      fontWeight: 500,
                      fontSize: 22,
                    }}>
                    <span>{f.q}</span>
                    <span style={{
                      fontFamily: "var(--ui)",
                      fontSize: 24,
                      fontStyle: "normal",
                      transform: open === i ? "rotate(45deg)" : "rotate(0)",
                      transition: "transform .2s",
                      opacity: 0.7,
                    }}>+</span>
                  </button>
                  {open === i && (
                    <div style={{
                      paddingBottom: 22,
                      opacity: 0.82,
                      lineHeight: 1.6,
                      maxWidth: "60ch",
                    }}>{f.a}</div>
                  )}
                </div>
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

/* -------------------- Gallery -------------------- */
function Gallery() {
  // Stylized image tiles using picsum + warm filter overlay + caption.
  const tiles = [
    { src: "img/stall-radishes.png", caption: "Spring onions & radishes", market: "Tustin · May" },
    { src: "img/peaches.jpg",        caption: "Peach baskets",            market: "Costa Mesa · Jun" },
    { src: "img/berries.jpg",        caption: "Berry pints, all in",      market: "Irvine · Jul" },
    { src: "img/stall-carrots.png",  caption: "Carrots, beets, chard",    market: "Tustin · Apr" },
    { src: "img/plums.jpg",          caption: "Divine — really, really juicy", market: "Laguna Hills · Aug" },
    { src: "img/aerial-market.png",  caption: "A full lot, mid-morning",  market: "Irvine · Jul" },
  ];
  return (
    <section id="gallery">
      <div className="wrap">
        <SectionHead
          eyebrow="Through the seasons"
          title={<>Postcards from <em>the lot.</em></>}
          lede="Forty Saturdays a year, give or take. Here are a few moments we've kept."
        />
        <div style={{
          display: "grid",
          gridTemplateColumns: "repeat(auto-fit, minmax(260px, 1fr))",
          gap: 24,
        }}>
          {tiles.map((t, i) => (
            <figure key={i} style={{
              margin: 0,
              aspectRatio: i % 3 === 0 ? "4 / 5" : "3 / 4",
              position: "relative",
              overflow: "hidden",
              background: "var(--bg-2)",
              borderRadius: 4,
            }}>
              <img
                src={t.src || `https://picsum.photos/seed/ocfm-${t.seed}/600/800`}
                alt={t.caption}
                style={{
                  width: "100%", height: "100%", objectFit: "cover",
                  filter: "sepia(0.14) saturate(0.94) brightness(0.98) contrast(1.04)",
                }}
                loading="lazy"
              />
              <figcaption style={{
                position: "absolute", left: 0, right: 0, bottom: 0,
                padding: "16px 18px",
                background: "linear-gradient(to top, rgba(31,36,24,0.75), transparent)",
                color: "var(--cream-warm)",
              }}>
                <div className="display" style={{ fontSize: 24, lineHeight: 1.05 }}>{t.caption}</div>
                <div className="tiny" style={{ color: "rgba(255,255,255,0.7)", marginTop: 4 }}>
                  {t.market}
                </div>
              </figcaption>
            </figure>
          ))}
        </div>
      </div>
    </section>
  );
}

/* -------------------- Newsletter + Footer -------------------- */
function Footer() {
  const [email, setEmail] = _u3("");
  const [subscribed, setSub] = _u3(false);
  return (
    <footer style={{ background: "var(--bg-2)", paddingBottom: 48, position: "relative", zIndex: 2 }}>
      <section id="contact" style={{ paddingTop: "clamp(72px, 9vw, 120px)" }}>
        <div className="wrap" style={{
          display: "grid",
          gridTemplateColumns: "1.5fr 1fr",
          gap: 48,
          alignItems: "start",
        }}>
          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>The newsletter</div>
            <h3 className="display" style={{
              fontSize: "clamp(40px, 5vw, 68px)",
              margin: 0, lineHeight: 0.96,
            }}>
              What's <em>coming in</em><br/>this week.
            </h3>
            <p className="lede" style={{ marginTop: 18, maxWidth: "44ch" }}>
              A short Tuesday email — what's at peak, who's new, weather notes,
              one recipe. No spam, no upsell.
            </p>
            {subscribed ? (
              <p style={{ marginTop: 24, fontStyle: "italic", color: "var(--green)" }}>
                Thanks — you'll get the next one Tuesday morning.
              </p>
            ) : (
              <form
                onSubmit={(e) => { e.preventDefault(); if (/\S+@\S+\.\S+/.test(email)) setSub(true); }}
                style={{
                  marginTop: 24,
                  display: "flex", gap: 8, maxWidth: 460,
                }}>
                <input
                  type="email" required
                  value={email} onChange={(e) => setEmail(e.target.value)}
                  placeholder="you@email.com"
                  style={{ flex: 1 }}
                />
                <button className="btn" type="submit">Subscribe</button>
              </form>
            )}
          </div>
          <div>
            <div className="eyebrow" style={{ marginBottom: 18 }}>Get in touch</div>
            <div style={{ fontSize: 16, lineHeight: 1.7 }}>
              <div><strong>Market manager</strong></div>
              <div>Susan Ward</div>
              <div><a href="mailto:susan@ocsbestmarkets.com" style={{ color: "var(--terracotta)" }}>susan@ocsbestmarkets.com</a></div>
              <div>(714) 555-0142</div>
              <div style={{ marginTop: 18 }}>
                <a href="#" style={{ color: "var(--ink)", textDecoration: "none", borderBottom: "1px solid var(--rule)" }}>Instagram</a>
                {" · "}
                <a href="#" style={{ color: "var(--ink)", textDecoration: "none", borderBottom: "1px solid var(--rule)" }}>Facebook</a>
              </div>
            </div>
          </div>
        </div>
      </section>

      <div className="wrap" style={{
        marginTop: 80,
        paddingTop: 28,
        borderTop: "1px solid var(--rule)",
        display: "flex", justifyContent: "space-between", flexWrap: "wrap", gap: 16,
        fontFamily: "var(--ui)", fontSize: 13, color: "var(--ink-soft)",
      }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
          <LogoMark size={22}/>
          <span>OC's Best Farmers Markets · est. 1989</span>
        </div>
        <div>© 2026 OC's Best Farmers Markets · A family business</div>
      </div>
    </footer>
  );
}

Object.assign(window, {
  Hero, Schedule, MapSection, InSeason, Vendors, Apply, About, Gallery, Footer,
});
