/* global React, DEMO_PHOTOS, PageHero */

// Neutral fallback swatch for quartz colours (real slab photos load over it;
// the gradient only shows if a photo is missing).
const Q = "linear-gradient(135deg, #f4f2ee, #ded8cf)";

// Photos for a colour are discovered by its `slug` from /images/:
//   [slug]-slab.jpg (main), [slug]-close.jpg, [slug]-close-2.jpg, [slug]-1.jpg ...
// Drop more files with the same slug and they appear automatically (see imageUrls()).
const MATERIALS = [
  {
    id: "quartz",
    name: "Quartz",
    tagline: "The everyday luxury.",
    desc: "Ninety-three percent crushed natural quartz, seven percent resin and pigment. The result is a worktop that looks like stone, behaves like a laboratory surface, and asks almost nothing of you for thirty years. Our most-fitted material  -  and for good reason.",
    cls: "stone-quartz",
    showpiece: "quartz-circe", // slab shown as the big tile on the main pages
    props: ["Non-porous", "Scratch resistant", "Low maintenance", "No sealing"],
    suits: "Busy family kitchens, islands, splashbacks.",
    cap: "Not for outdoor use  -  resin degrades in direct UV.",
    // Fasa Stone quartz range — photos in /images/ as quartz-[slug]-slab.jpg etc.
    // bracket = pricing tier (1 standard · 2 premium · 3 super-premium). All set
    // to 1 as a placeholder — TODO: Sean to confirm the real tier per colour.
    // Two ranges (same quality, different pricing): "Zeal" (bracket 1) and "Exo"
    // (bracket 2 — small uplift). only20mm flags stones we only stock at 20mm.
    colours: [
      { name: "Ariston",          slug: "quartz-ariston",          swatch: Q, bracket: 2 },
      { name: "Armelia",          slug: "quartz-armelia",          swatch: Q, bracket: 2 },
      { name: "Artic",            slug: "quartz-artic",            swatch: Q, bracket: 1 },
      { name: "Calescato",        slug: "quartz-calescato",        swatch: Q, bracket: 2 },
      { name: "Carmen",           slug: "quartz-carmen",           swatch: Q, bracket: 2, only20mm: true },
      { name: "Circe",            slug: "quartz-circe",            swatch: Q, bracket: 1 },
      { name: "Dalai",            slug: "quartz-dalai",            swatch: Q, bracket: 1 },
      { name: "Eirene",           slug: "quartz-eirene",           swatch: Q, bracket: 1 },
      { name: "Fausto",           slug: "quartz-fausto",           swatch: Q, bracket: 2, only20mm: true },
      { name: "Fausto Full Body", slug: "quartz-fausto-full-body", swatch: Q, bracket: 2 },
      { name: "Georgia",          slug: "quartz-georgia",          swatch: Q, bracket: 1 },
      { name: "Iceberg",          slug: "quartz-iceberg",          swatch: Q, bracket: 1 },
      { name: "K2",               slug: "quartz-k2",               swatch: Q, bracket: 2, only20mm: true },
      { name: "Kells",            slug: "quartz-kells",            swatch: Q, bracket: 1 },
      { name: "Liberty",          slug: "quartz-liberty",          swatch: Q, bracket: 2 },
      { name: "Muse",             slug: "quartz-muse",             swatch: Q, bracket: 2 },
      { name: "Norma",            slug: "quartz-norma",            swatch: Q, bracket: 2, only20mm: true },
      { name: "Paradise",         slug: "quartz-paradise",         swatch: Q, bracket: 2 },
      { name: "Patagonia",        slug: "quartz-patagonia",        swatch: Q, bracket: 1 },
      { name: "Rhapsody",         slug: "quartz-rhapsody",         swatch: Q, bracket: 1 },
      { name: "River Deep",       slug: "quartz-river-deep",       swatch: Q, bracket: 1 },
      { name: "Sonoro",           slug: "quartz-sonoro",           swatch: Q, bracket: 2, only20mm: true },
      { name: "Sweet Caroline",   slug: "quartz-sweet-caroline",   swatch: Q, bracket: 1 },
      { name: "Tagore",           slug: "quartz-tagore",           swatch: Q, bracket: 1 },
      { name: "Taj",              slug: "quartz-taj",              swatch: Q, bracket: 2, only20mm: true },
      { name: "Teresa",           slug: "quartz-teresa",           swatch: Q, bracket: 2 },
      { name: "Tosca",            slug: "quartz-tosca",            swatch: Q, bracket: 2 },
      { name: "Violuxe",          slug: "quartz-violuxe",          swatch: Q, bracket: 2 },
      { name: "White Shimmer",    slug: "quartz-white-shimmer",    swatch: Q, bracket: 1 },
      { name: "White Water",      slug: "quartz-white-water",      swatch: Q, bracket: 1 },
      { name: "Belvedere",        slug: "quartz-belvedere",        swatch: Q, bracket: 2 },
      { name: "BVLGARI",          slug: "quartz-bvlgari",          swatch: Q, bracket: 1 },
      { name: "Frozen",           slug: "quartz-frozen",           swatch: Q, bracket: 1 },
      { name: "Layla",            slug: "quartz-layla",            swatch: Q, bracket: 1 },
      { name: "Mercury",          slug: "quartz-mercury",          swatch: "linear-gradient(135deg, #b9bcbe, #7e8488)", bracket: 1 },
      { name: "Misty Brown",      slug: "quartz-misty-brown",      swatch: "linear-gradient(135deg, #c9bdae, #8d8071)", bracket: 1 },
      { name: "Otello",           slug: "quartz-otello",           swatch: Q, bracket: 2, only20mm: true },
      { name: "Peace",            slug: "quartz-peace",            swatch: Q, bracket: 2, only20mm: true },
      { name: "Rigoletto",        slug: "quartz-rigoletto",        swatch: Q, bracket: 2, only20mm: true },
      { name: "Uyuni",            slug: "quartz-uyuni",            swatch: Q, bracket: 1 },
      { name: "Victoria",         slug: "quartz-victoria",         swatch: Q, bracket: 1 },
    ],
  },
  {
    id: "granite",
    name: "Granite",
    tagline: "The original.",
    desc: "Drawn from the earth, sawn into slabs, polished by hand. No two pieces are ever alike.",
    cls: "stone-granite",
    showpiece: "granite-perecimo", // slab shown as the big tile on the main pages
    props: ["Heat resistant", "Extremely durable", "Unique veining"],
    suits: "Heavy-use kitchens, outdoor counters, fireplaces.",
    cap: "Some dark granites can show watermarks until sealed.",
    // Only the colours we currently stock/have photos for. Add more with the
    // same slug convention (granite-[colour]-slab.jpg / -close.jpg).
    colours: [
      { name: "Jet Black", slug: "granite-jet-black", swatch: "linear-gradient(135deg, #1a1a1a, #050505)", bracket: 1 },
      { name: "BG Black",  slug: "granite-bg-black",  swatch: "linear-gradient(135deg, #1b1815, #060504)", bracket: 1 },
      { name: "Perecimo",  slug: "granite-perecimo",  swatch: "linear-gradient(135deg, #6f6a63, #36322d)", bracket: 1 },
    ],
  },
  {
    id: "porcelain",
    hidden: true, // PORCELAIN_HIDDEN — restore when stock is sufficient
    name: "Porcelain",
    tagline: "The modern hard-case.",
    desc: "Fired at 1,200C into a sheet harder than granite and lighter than quartz. The colours go through the body, the surface is impervious, and the finish is crisp, slim and architectural. The choice for modern kitchens and outdoor counters.",
    cls: "stone-porcelain",
    props: ["Heat-proof", "UV stable", "Stain proof", "3mm or 12mm slab", "Indoor + outdoor"],
    suits: "Minimalist kitchens, outdoor BBQs, vanity tops.",
    cap: "Thinner slabs require expert handling  -  which we have.",
    colours: [
      { name: "Statuario", swatch: "linear-gradient(135deg, #f7f7f3 0 38%, #8b9295 39% 41%, #f1f0ea 42% 100%)", photo: "/images/porcelain-statuario.jpg", bracket: 1 },
      { name: "Calacatta", swatch: "linear-gradient(135deg, #fbfaf4, #d0b16e 34%, #f2efe5 38%, #ffffff)", photo: "/images/porcelain-calacatta.jpg", bracket: 1 },
      { name: "Travertine", swatch: "repeating-linear-gradient(0deg, #d2c2ad 0 8px, #bca98f 9px 11px, #e3d6c3 12px 20px)", photo: "/images/porcelain-travertine.jpg", bracket: 1 },
      { name: "Concrete", swatch: "linear-gradient(135deg, #b4b7b8, #7d8387)", photo: "/images/porcelain-concrete.jpg", bracket: 1 },
      { name: "Basalt", swatch: "linear-gradient(135deg, #43484c, #171a1e)", photo: "/images/porcelain-basalt.jpg", bracket: 1 },
      { name: "Iron Grey", swatch: "linear-gradient(135deg, #55585a, #24272a 48%, #73706c 50%, #333638)", photo: "/images/porcelain-iron-grey.jpg", bracket: 1 },
    ],
  },
];

function Materials({ navigate }) {
  const visibleMaterials = MATERIALS.filter(m => !m.hidden); // PORCELAIN_HIDDEN
  return (
    <React.Fragment>
      {/* Hero */}
      <section style={{padding: "var(--pad)", paddingTop: "clamp(118px, 13vw, 170px)", paddingBottom: "clamp(48px, 5vw, 76px)", background: "var(--warm)"}}>
        <div className="container">
          <div className="kicker" style={{marginBottom: 24}}>The Lookbook - Three core materials</div>
          <h1 className="display" style={{color: "var(--navy)", maxWidth: 1100}}>
            Stone, as<br /><em className="pull" style={{color: "var(--teal)"}}>it should be chosen.</em>
          </h1>
          <p className="lede" style={{maxWidth: 640, marginTop: 28, fontSize: 18}}>
            Below is an honest introduction to the core materials we hold and fit in volume - what each one is for, what it is not, and where it shines. Tap any material to browse its colours close-up, then come and see them in person at our Kilbeggan yard.
          </p>
        </div>
      </section>

      {/* Quick index */}
      <section style={{padding: "0 var(--pad) 60px"}}>
        <div className="container material-index" style={{display: "flex", gap: 16, flexWrap: "wrap", borderTop: "1px solid var(--line)", paddingTop: 32}}>
          {visibleMaterials.map((m, i) => (
            <a key={m.id} href={`#mat-${m.id}`} style={{
              display: "flex", alignItems: "center", gap: 14,
              padding: "10px 0", flex: 1, minWidth: 160,
            }}>
              <div className={`stone ${m.cls}`} style={{width: 40, height: 40, borderRadius: 2}}></div>
              <div>
                <div className="kicker" style={{color: "var(--grey)", marginBottom: 2}}>0{i + 1}</div>
                <div style={{fontFamily: "var(--serif)", fontSize: 19, color: "var(--navy)"}}>{m.name}</div>
              </div>
            </a>
          ))}
        </div>
      </section>

      {/* Material sections */}
      {visibleMaterials.map((m, i) => {
        const isReverse = i % 2 === 1;
        return (
          <section key={m.id} id={`mat-${m.id}`} style={{
            background: i % 2 === 0 ? "var(--warm)" : "var(--light-teal)",
            padding: "clamp(80px, 9vw, 140px) var(--pad)",
          }}>
            <div className="container">
              <div className="material-section-grid" style={{
                display: "grid", gridTemplateColumns: "1fr 1fr",
                gap: 80, alignItems: "center",
                direction: isReverse ? "rtl" : "ltr",
              }}>
                <div style={{direction: "ltr"}}>
                  <a href={`#/materials/${m.id}`}
                     className="material-tile-link"
                     aria-label={`Browse ${m.name} colours`}
                     onClick={(e) => { e.preventDefault(); navigate(`materials/${m.id}`); }}>
                    <div className={`stone ${m.cls}`} style={{
                      aspectRatio: "1/1", borderRadius: 2, position: "relative", overflow: "hidden",
                      boxShadow: "0 30px 80px -30px rgba(15,37,53,0.3)",
                    }}>
                      {m.showpiece && <img src={`/images/${m.showpiece}-slab.jpg`} alt={m.name}
                        style={{position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover"}}
                        onError={(e) => { e.currentTarget.style.display = "none"; }} />}
                    </div>
                    <span className="material-tile-cta">Browse {m.name.toLowerCase()} colours <span>{"->"}</span></span>
                  </a>
                </div>

                <div style={{direction: "ltr"}}>
                  <div className="kicker" style={{marginBottom: 16}}>0{i + 1} - {m.tagline}</div>
                  <h2 className="title" style={{color: "var(--navy)"}}>{m.name}</h2>
                  <p style={{marginTop: 28, fontSize: 17, lineHeight: 1.65, color: "var(--slate)", maxWidth: 520}}>
                    {m.desc}
                  </p>

                  {/* Properties grid */}
                  <div style={{display: "grid", gridTemplateColumns: "repeat(2, 1fr)", gap: "12px 24px", marginTop: 40, maxWidth: 520}}>
                    {m.props.map((p, j) => (
                      <div key={j} style={{display: "flex", alignItems: "center", gap: 12, padding: "10px 0", borderBottom: "1px solid rgba(27,61,90,0.08)"}}>
                        <svg width="14" height="14" viewBox="0 0 14 14"><path d="M2 7l3 3 7-7" stroke="#2A8CAA" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
                        <span style={{fontSize: 13.5, color: "var(--slate)", fontWeight: 500}}>{p}</span>
                      </div>
                    ))}
                  </div>

                  <div style={{marginTop: 36, padding: "20px 24px", background: "rgba(255,255,255,0.5)", borderLeft: "2px solid var(--teal)"}}>
                    <div className="kicker" style={{color: "var(--teal)", marginBottom: 8}}>Best for</div>
                    <div style={{fontSize: 14.5, color: "var(--navy)", marginBottom: 16}}>{m.suits}</div>
                    <div className="kicker" style={{color: "var(--grey)", marginBottom: 8}}>Honest caveat</div>
                    <div style={{fontSize: 13, color: "var(--grey)"}}>{m.cap}</div>
                  </div>

                  <div className="colour-panel">
                    <a className="btn btn-teal"
                       href={`#/materials/${m.id}`}
                       onClick={(e) => { e.preventDefault(); navigate(`materials/${m.id}`); }}>
                      Browse all {m.name.toLowerCase()} colours <span className="arr">{"->"}</span>
                    </a>
                    <div style={{marginTop: 12, fontSize: 13.5, color: "var(--grey)"}}>
                      {m.colours.length} popular colours with photos · more to see in person at the yard
                    </div>
                  </div>

                  <a className="btn-text" href="#/work" onClick={(e) => { e.preventDefault(); navigate("work"); }} style={{marginTop: 36, display: "inline-flex"}}>
                    See projects in {m.name.toLowerCase()} <span>{"->"}</span>
                  </a>
                </div>
              </div>
            </div>
          </section>
        );
      })}

      {/* Showroom CTA */}
      <section className="section deep">
        <div className="container showroom-grid" style={{display: "grid", gridTemplateColumns: "1fr 1fr", gap: 80, alignItems: "center"}}>
          <div>
            <div className="kicker" style={{color: "#7CC3D8", marginBottom: 20}}>The showroom</div>
            <h2 className="title" style={{color: "white"}}>
              Not sure which<br /><em className="pull" style={{color: "#7CC3D8"}}>Come to Kilbeggan.</em>
            </h2>
            <p style={{marginTop: 32, fontSize: 17, lineHeight: 1.6, color: "rgba(255,255,255,0.8)", maxWidth: 500}}>
              Quartz, granite and ceramic slabs on rotating display in our yard, lit at kitchen-counter height. You walk between them, we answer questions, nobody pressures you. An hour from Dublin, fifty minutes from Galway.
            </p>
            <div style={{marginTop: 44, display: "flex", gap: 14, flexWrap: "wrap"}}>
              <a className="btn btn-teal" href="#/booking" onClick={(e) => { e.preventDefault(); navigate("booking"); }}>Book a Showroom Visit <span className="arr">{"->"}</span></a>
              <a className="btn btn-ghost" href="#/story" onClick={(e) => { e.preventDefault(); navigate("story"); }}>About the Factory</a>
            </div>
          </div>

          <div className="demo-photo-card" style={{aspectRatio: "4/5", backgroundImage: `url(${DEMO_PHOTOS.showroom})`}}>
            <span className="lbl">Slabs on display, Kilbeggan yard</span>
          </div>
        </div>
      </section>
    </React.Fragment>
  );
}

/* ============================================================
   MaterialColours — per-material colour viewer (#/materials/:id)
   Photos live in /images/[material-id]-[colour-slug].jpg.
   Each card layers the real photo over its CSS swatch; if the photo
   is missing the <img> onError hides it and the swatch shows through,
   so Sean can drop images into /images/ with no code change.
   ============================================================ */
// Main thumbnail for a colour: the slab photo (by slug) or a legacy single photo.
function slabUrl(c) {
  return c.slug ? "/images/" + c.slug + "-slab.jpg" : (c.photo || null);
}
// Candidate gallery URLs to probe for a colour, in display order (slab first).
function candidateUrls(c) {
  if (c.slug) {
    const b = "/images/" + c.slug;
    return ["-slab", "-close", "-close-2", "-close-3", "-1", "-2", "-3", "-4", "-5", "-6", "-7", "-8"].map(s => b + s + ".jpg");
  }
  return c.photo ? [c.photo] : [];
}

function MaterialColours({ materialId, navigate }) {
  const material = MATERIALS.find(m => m.id === materialId && !m.hidden);
  const [active, setActive]   = React.useState(null); // colour object for the lightbox
  const [gallery, setGallery] = React.useState([]);   // photo URLs that loaded, in order
  const [slide, setSlide]     = React.useState(0);
  const touchX = React.useRef(null);

  // Probe the candidate photos for the open colour; keep the ones that load.
  // Drop more files with the same slug and they appear here automatically.
  React.useEffect(() => {
    if (!active) { setGallery([]); setSlide(0); return; }
    let cancelled = false;
    Promise.all(candidateUrls(active).map(url => new Promise(res => {
      const img = new Image();
      img.onload  = () => res(url);
      img.onerror = () => res(null);
      img.src = url;
    }))).then(found => { if (!cancelled) { setGallery(found.filter(Boolean)); setSlide(0); } });
    return () => { cancelled = true; };
  }, [active]);

  // Keyboard: Esc closes, arrows page the carousel
  React.useEffect(() => {
    if (!active) return;
    const onKey = (e) => {
      if (e.key === "Escape") setActive(null);
      else if (e.key === "ArrowRight") setSlide(s => gallery.length ? (s + 1) % gallery.length : 0);
      else if (e.key === "ArrowLeft")  setSlide(s => gallery.length ? (s - 1 + gallery.length) % gallery.length : 0);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [active, gallery.length]);

  const goMaterials = (e) => { e.preventDefault(); navigate("materials"); };
  const goQuotes    = (e) => { e.preventDefault(); setActive(null); navigate("quotes"); };

  // Unknown / mistyped material id — fail gracefully back to the index
  if (!material) {
    return (
      <React.Fragment>
        <PageHero
          kicker="Materials"
          title="That colour range wasn't found."
          sub="Browse our full set of materials and colours instead."
        />
        <section className="section">
          <div className="container">
            <a className="btn btn-teal" href="#/materials" onClick={goMaterials}>
              Back to materials <span className="arr">{"->"}</span>
            </a>
          </div>
        </section>
      </React.Fragment>
    );
  }

  const hideOnError = (e) => { e.currentTarget.style.display = "none"; };

  return (
    <React.Fragment>
      <PageHero
        kicker={`Materials · ${material.name}`}
        title={
          <React.Fragment>
            {material.name} colours.<br />
            <em className="pull" style={{color: "#7CC3D8"}}>{material.tagline}</em>
          </React.Fragment>
        }
        sub={material.suits ? `Best for ${material.suits.charAt(0).toLowerCase() + material.suits.slice(1)}` : undefined}
      />

      <section className="section">
        <div className="container" style={{maxWidth: 1100}}>
          <a className="btn-text" href="#/materials" onClick={goMaterials} style={{display: "inline-flex", marginBottom: 26}}>
            <span style={{marginRight: 6}}>{"<-"}</span> All materials
          </a>

          <p className="lede" style={{maxWidth: 660, fontSize: 17}}>
            A selection of our most-requested {material.name.toLowerCase()} colours. Every slab is unique — these are a guide, and the full range is on display at our Kilbeggan yard. Tap any colour to see it larger.
          </p>

          <div className="mc-grid">
            {material.colours.map(c => (
              <button type="button" key={c.name} className="mc-card" onClick={() => setActive(c)}>
                <div className="mc-thumb" style={{background: c.swatch}}>
                  {slabUrl(c) && <img src={slabUrl(c)} alt={c.name} loading="lazy" onError={hideOnError} />}
                </div>
                <div className="mc-name">{c.name}</div>
              </button>
            ))}
          </div>

          <div className="mc-cta">
            <div>
              <div className="kicker" style={{color: "var(--teal)", marginBottom: 10}}>Found one you like?</div>
              <div style={{fontFamily: "var(--serif)", fontSize: 26, color: "var(--navy)", lineHeight: 1.2}}>
                Get a quote in this colour
              </div>
            </div>
            <a className="btn btn-teal" href="#/quotes" onClick={goQuotes}>
              Get a quote <span className="arr">{"->"}</span>
            </a>
          </div>
        </div>
      </section>

      {active && (
        <div className="mc-lightbox" role="dialog" aria-modal="true" aria-label={active.name}
             onClick={() => setActive(null)}>
          <div className="mc-lightbox-inner" onClick={(e) => e.stopPropagation()}>
            <button type="button" className="mc-lightbox-close" aria-label="Close" onClick={() => setActive(null)}>×</button>
            <div className="mc-carousel"
              onTouchStart={(e) => { touchX.current = e.touches[0].clientX; }}
              onTouchEnd={(e) => {
                if (touchX.current == null || gallery.length < 2) return;
                const dx = e.changedTouches[0].clientX - touchX.current;
                if (Math.abs(dx) > 40) setSlide(s => dx < 0 ? (s + 1) % gallery.length : (s - 1 + gallery.length) % gallery.length);
                touchX.current = null;
              }}>
              <div className="mc-lightbox-img" style={{background: active.swatch}}>
                {gallery[slide] && <img src={gallery[slide]} alt={active.name + " — view " + (slide + 1)} />}
              </div>
              {gallery.length > 1 && (
                <React.Fragment>
                  <button type="button" className="mc-nav prev" aria-label="Previous"
                    onClick={() => setSlide(s => (s - 1 + gallery.length) % gallery.length)}>‹</button>
                  <button type="button" className="mc-nav next" aria-label="Next"
                    onClick={() => setSlide(s => (s + 1) % gallery.length)}>›</button>
                  <div className="mc-dots">
                    {gallery.map((_, i) => (
                      <button type="button" key={i} aria-label={"View " + (i + 1)}
                        className={"mc-dot" + (i === slide ? " on" : "")} onClick={() => setSlide(i)} />
                    ))}
                  </div>
                </React.Fragment>
              )}
            </div>
            <div className="mc-lightbox-meta">
              <div className="mc-lightbox-sub">{material.name}{gallery.length > 1 ? ` · ${slide + 1} of ${gallery.length}` : ""}</div>
              <div className="mc-lightbox-name">{active.name}</div>
              <a className="btn-text" href="#/quotes" onClick={goQuotes} style={{marginTop: 14, display: "inline-flex"}}>
                Get a quote in {active.name} <span style={{marginLeft: 6}}>{"->"}</span>
              </a>
            </div>
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

window.Materials = Materials;
window.MaterialColours = MaterialColours;
window.MATERIALS = MATERIALS;
