/* VSHD pages: Home, Projects, CaseStudy (Origami), plus placeholders */

const { useState: _useState, useEffect: _useEffect, useMemo: _useMemo, useRef: _useRef } = React;

/* ================= HOME ================= */
function Home({ go, onOpenEnquiry, tweaks }) {
  const heroes = window.VSHD_HERO;
  const projects = window.VSHD_PROJECTS;
  const [idx, setIdx] = _useState(0);
  const [progress, setProgress] = _useState(0);
  const durMs = (tweaks.heroPaceSec || 7) * 1000;

  _useEffect(() => {
    setProgress(0);
    const started = Date.now();
    const tick = setInterval(() => {
      const p = (Date.now() - started) / durMs;
      if (p >= 1) {
        setIdx((i) => (i + 1) % heroes.length);
        setProgress(0);
      } else {
        setProgress(p);
      }
    }, 40);
    return () => clearInterval(tick);
  }, [idx, durMs, heroes.length]);

  const heroProj = projects.find(p => p.slug === heroes[idx].slug) || projects[0];

  // Selected work — curated 4 (matches the staggered editorial grid)
  const selected = [
    projects.find(p => p.slug === "origami"),
    projects.find(p => p.slug === "klei-spa"),
    projects.find(p => p.slug === "burj-residence"),
    projects.find(p => p.slug === "hoof")
  ].filter(Boolean);

  // Sector counts
  const sectorCounts = {};
  projects.forEach(p => { sectorCounts[p.sector] = (sectorCounts[p.sector] || 0) + 1; });
  const sectorList = [
    { key: "Residential", num: "01" },
    { key: "Hospitality", num: "02", label: "Hospitality & F&B" },
    { key: "Workplace",   num: "03" },
    { key: "Retail",      num: "04" },
    { key: "Wellness",    num: "05" },
    { key: "Fitness",     num: "06" }
  ];

  return (
    <div data-screen-label="01 Home">
      {/* HERO */}
      <section className="hero" data-screen-label="01 Home · Hero">
        {heroes.map((h, i) => {
          const proj = projects.find(p => p.slug === h.slug);
          return (
            <div key={h.slug} className={"hero__slide " + (i === idx ? "is-active" : "")} aria-hidden={i !== idx}>
              <img className="hero__img" src={proj.cover} alt="" />
              <div className="hero__veil" />
            </div>
          );
        })}

        <span className="hero__corner">VSHD · Est. 2007 · Dubai &nbsp;/&nbsp; Montréal</span>

        <div className="hero__overlay">
          <div className="hero__caption">
            <div>
              <p className="cap" style={{ color: "rgba(255,255,255,.7)", marginBottom: 14 }}>
                {heroes[idx].sector} &nbsp;·&nbsp; {heroes[idx].location}
              </p>
              <h1 className="hero__title">
                Interior architecture<br/>
                of <em>calm, beauty</em> &amp;<br/>
                subtle luxury.
              </h1>
              <div style={{ marginTop: 28, display: "flex", gap: 14, flexWrap: "wrap" }}>
                <button className="btn btn--light" onClick={() => go("projects")}>
                  See selected work <span className="arrow" />
                </button>
                <button className="btn btn--light" onClick={onOpenEnquiry}>
                  Start a project
                </button>
              </div>
            </div>

            <div className="hero__meta" style={{ alignSelf: "end", textAlign: "right" }}>
              <div>
                <span style={{ opacity: .6, marginRight: 8 }}>Now showing</span>
                <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic", textTransform: "none", letterSpacing: 0, fontSize: 14 }}>
                  {heroes[idx].caption}
                </span>
              </div>
            </div>
          </div>
        </div>

        <div className="hero__progress" role="tablist">
          {heroes.map((h, i) => (
            <button
              key={h.slug}
              onClick={() => setIdx(i)}
              aria-label={"Show " + h.caption}
              style={{ "--p": i < idx ? "100%" : i === idx ? (progress * 100) + "%" : "0%" }}
            />
          ))}
        </div>
      </section>

      {/* SELECTED WORK */}
      <section className="section" data-screen-label="01 Home · Selected Work">
        <div className="section__head">
          <div>
            <p className="eyebrow">Selected work · 2017—2024</p>
            <h2 className="h-section" style={{ marginTop: 18 }}>
              A practice <em>told</em> through<br/>twenty-five places.
            </h2>
          </div>
          <div>
            <p className="lede">
              We work slowly and at boutique scale — typically six to eight
              commissions a year — across residence, restaurant, workplace and
              wellness. Each project is photographed, written and credited as a
              case study.
            </p>
            <button className="link-underline" onClick={() => go("projects")} style={{ marginTop: 18, fontSize: 12, letterSpacing: ".22em", textTransform: "uppercase" }}>
              View all twenty-five projects →
            </button>
          </div>
        </div>

        <div className="work-grid">
          {selected.map((p, i) => (
            <a
              key={p.slug}
              className={"work-tile work-tile--0" + (i + 1)}
              onClick={() => go("project/" + p.slug)}
              role="link"
              tabIndex="0"
            >
              <div className="work-tile__frame">
                <img src={p.cover} alt={p.name} loading="lazy" />
              </div>
              <div className="work-tile__meta">
                <div>
                  <div>{p.name}</div>
                  <div className="cap" style={{ marginTop: 4 }}>{p.location}</div>
                </div>
                <span className="cap">{p.sector} · {p.year}</span>
              </div>
            </a>
          ))}
        </div>
      </section>

      {/* APPROACH — dark inverted */}
      <section className="section section--dark" data-screen-label="01 Home · Approach">
        <div className="approach">
          <div>
            <p className="eyebrow">Approach</p>
            <h2 className="h-section" style={{ marginTop: 18, color: "#fff" }}>
              Four pillars,<br/>
              <em>quietly</em> held.
            </h2>
            <p className="lede" style={{ marginTop: 24 }}>
              From Rania Hamed's own writing on the studio: a slow practice
              guided by four convictions. They have not changed since 2007.
            </p>
          </div>

          <ol className="pillar-list" style={{ margin: 0, padding: 0, listStyle: "none" }}>
            <li className="pillar">
              <span className="pillar__num">01</span>
              <div>
                <h3 className="pillar__title">Timelessness <em>over</em> trend.</h3>
                <p className="pillar__body">
                  We design for longevity. Visualisations are not trend-led but
                  synonymous with timelessness — calm rooms that age into
                  themselves.
                </p>
              </div>
            </li>
            <li className="pillar">
              <span className="pillar__num">02</span>
              <div>
                <h3 className="pillar__title">Light as <em>a</em> material.</h3>
                <p className="pillar__body">
                  We transform the space through the creative use of light —
                  natural, electric, reflected — treated with the same care as
                  stone, timber or plaster.
                </p>
              </div>
            </li>
            <li className="pillar">
              <span className="pillar__num">03</span>
              <div>
                <h3 className="pillar__title">Tradition <em>×</em> contemporary.</h3>
                <p className="pillar__body">
                  Integrating traditional culture and technique into
                  contemporary design — craft from the region carried forward
                  on a modern grid.
                </p>
              </div>
            </li>
            <li className="pillar">
              <span className="pillar__num">04</span>
              <div>
                <h3 className="pillar__title">Subtle <em>luxury</em>.</h3>
                <p className="pillar__body">
                  Combining modesty with elegance to reach elements of
                  calm, beauty and subtle luxury — what the eye notices last
                  is often the most considered.
                </p>
              </div>
            </li>
          </ol>
        </div>
      </section>

      {/* SECTORS */}
      <section className="section">
        <div className="section__head section__head--single" style={{ marginBottom: 32 }}>
          <p className="eyebrow">Sectors</p>
          <h2 className="h-section" style={{ marginTop: 18, maxWidth: 22 + "ch" }}>
            Six typologies. One <em>standard</em>.
          </h2>
        </div>
        <div className="sectors-strip">
          {sectorList.map((s) => {
            const count = sectorCounts[s.key] || 0;
            return (
              <div key={s.key} className="sector-cell" onClick={() => go("projects?s=" + s.key)}>
                <span className="sector-cell__num">{s.num} ·</span>
                <span className="sector-cell__name">{s.label || s.key}</span>
                <span className="sector-cell__count">{count ? String(count).padStart(2, "0") : "—"} projects</span>
              </div>
            );
          })}
        </div>
      </section>

      {/* AWARDS */}
      <section className="section section--bone">
        <div className="section__head">
          <div>
            <p className="eyebrow">Recognition</p>
            <h2 className="h-section" style={{ marginTop: 18 }}>
              Quiet, <em>repeated</em><br/>recognition.
            </h2>
          </div>
          <div>
            <p className="lede">
              A boutique studio with an international press and awards record.
              Listed by issuer, year and project — never bundled into a generic
              "award-winning" claim.
            </p>
          </div>
        </div>

        <div className="awards">
          <div>
            <p className="cap">As featured in</p>
            <div style={{ marginTop: 24, display: "flex", flexDirection: "column", gap: 14, fontSize: 18, lineHeight: 1.5, color: "var(--ink-soft)" }}>
              <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic" }}>Architectural Digest</span>
              <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic" }}>Vogue Arabia</span>
              <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic" }}>Harper's Bazaar Interiors</span>
              <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic" }}>Dezeen</span>
              <span style={{ fontFamily: "var(--font-serif)", fontStyle: "italic" }}>PLAIN Magazine</span>
            </div>
          </div>

          <div className="awards__list">
            {window.VSHD_AWARDS.map((a, i) => (
              <div className="award-row" key={i}>
                <span className="award-row__year">{a.year}</span>
                <span className="award-row__title">{a.title}<small>{a.sub}</small></span>
                <span className="award-row__issuer">{a.issuer}</span>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CTA BAND */}
      <section className="section" style={{ paddingBottom: 120 }}>
        <div className="cta-band">
          <div>
            <p className="eyebrow">Begin</p>
            <h2 className="h-section" style={{ marginTop: 18, maxWidth: 18 + "ch" }}>
              Brief us on a <em>place</em><br/>you'd like considered.
            </h2>
          </div>
          <div style={{ display: "flex", gap: 14, flexWrap: "wrap" }}>
            <button className="btn btn--solid" onClick={onOpenEnquiry}>Start a project <span className="arrow" /></button>
            <button className="btn" onClick={() => go("studio")}>Meet the studio</button>
          </div>
        </div>
      </section>

      <Footer onOpenEnquiry={onOpenEnquiry} go={go} />
    </div>
  );
}

/* ================= PROJECTS INDEX ================= */
function Projects({ go, onOpenEnquiry, initialSector }) {
  const projects = window.VSHD_PROJECTS;
  const sectors = window.VSHD_SECTORS;
  const [sector, setSector] = _useState(initialSector || "All");

  const sectorCounts = _useMemo(() => {
    const m = { All: projects.length };
    projects.forEach(p => { m[p.sector] = (m[p.sector] || 0) + 1; });
    return m;
  }, [projects]);

  const filtered = sector === "All" ? projects : projects.filter(p => p.sector === sector);

  // Editorial rhythm classes: 8/4, 4/8, 6/6, 6/6, then loop
  const rhythm = ["proj-card--wide", "proj-card--narrow", "proj-card--default", "proj-card--default"];

  return (
    <div data-screen-label="02 Projects">
      <header className="page-head">
        <div>
          <p className="eyebrow">Projects · Index</p>
          <h1 className="h-display" style={{ marginTop: 18 }}>
            <em>Twenty-five</em> places,<br/>case by case.
          </h1>
        </div>
        <div>
          <p className="page-head__count">{String(filtered.length).padStart(2, "0")}<span style={{ fontFamily: "var(--font-sans)", fontStyle: "normal", fontSize: 14, color: "var(--muted)", letterSpacing: ".18em", textTransform: "uppercase", marginLeft: 14 }}>showing</span></p>
          <p className="lede" style={{ marginTop: 24, fontSize: 15 }}>
            Filter by sector. Every project page carries its photographer
            credit, year, location and a written narrative — never a thumbnail
            alone.
          </p>
        </div>
      </header>

      <div className="sector-filter" role="tablist">
        {sectors.map(s => (
          <button
            key={s.key}
            role="tab"
            aria-selected={sector === s.key}
            className={sector === s.key ? "is-active" : ""}
            onClick={() => setSector(s.key)}
          >
            {s.label}
            <span className="ct">{sectorCounts[s.key] ? "(" + String(sectorCounts[s.key]).padStart(2, "0") + ")" : "(00)"}</span>
          </button>
        ))}
      </div>

      <div className="projects-grid">
        {filtered.map((p, i) => (
          <a
            key={p.slug}
            className={"proj-card " + rhythm[i % rhythm.length]}
            onClick={() => go("project/" + p.slug)}
            role="link"
            tabIndex="0"
          >
            <div className="proj-card__frame">
              <img src={p.cover} alt={p.name} loading="lazy" />
              <span className="proj-card__num">{String(i + 1).padStart(2, "0")}</span>
            </div>
            <div className="proj-card__meta">
              <div>
                <div className="proj-card__title">{p.name}</div>
                <div className="proj-card__sub">{p.location} · {p.year}</div>
              </div>
              <span className="proj-card__sector">{p.sector}</span>
            </div>
          </a>
        ))}
      </div>

      <Footer onOpenEnquiry={onOpenEnquiry} go={go} />
    </div>
  );
}

/* ================= CASE STUDY ================= */
function CaseStudy({ slug, go, onOpenEnquiry }) {
  const project = window.VSHD_PROJECTS.find(p => p.slug === slug);
  const [lightbox, setLightbox] = _useState(null);

  if (!project) {
    return (
      <div data-screen-label="03 Case Study · Missing" style={{ padding: "180px var(--pad-x)" }}>
        <p className="eyebrow">404</p>
        <h1 className="h-display" style={{ marginTop: 18 }}>Project not found.</h1>
        <button className="btn" style={{ marginTop: 32 }} onClick={() => go("projects")}>Back to projects</button>
      </div>
    );
  }

  // Origami gets the full narrative; other projects show a graceful shorter version
  const isOrigami = project.slug === "origami";

  // next/prev
  const list = window.VSHD_PROJECTS;
  const i = list.findIndex(p => p.slug === slug);
  const prev = list[(i - 1 + list.length) % list.length];
  const next = list[(i + 1) % list.length];

  // Hero image
  const heroImg = project.images && project.images[0] ? project.images[0] : project.cover;

  // Gallery — for Origami use its 3 location images plus the cover image rotation
  const galleryImages = (project.images && project.images.length > 1)
    ? project.images
    : [project.cover];

  // Padded list to 4 frames for visual rhythm — repeat if necessary
  const galleryFour = [];
  for (let k = 0; k < 4; k++) {
    galleryFour.push(galleryImages[k % galleryImages.length]);
  }

  return (
    <div data-screen-label={"03 Case Study · " + project.name}>
      {/* CS HERO */}
      <section className="cs-hero">
        <img className="cs-hero__img" src={heroImg} alt={project.name} />
        <div className="cs-hero__veil" />
        <div className="cs-hero__content">
          <p className="cs-hero__eyebrow">Case Study · {String(i + 1).padStart(2, "0")} · {project.sector}</p>
          <h1 className="cs-hero__title">
            {project.name.split(" · ")[0]}<br/>
            {project.location && (
              <em style={{ fontSize: ".55em", display: "inline-block", marginTop: 14 }}>
                {project.location.split(",")[0]}.
              </em>
            )}
          </h1>
        </div>
      </section>

      {/* META BAR */}
      <div className="cs-metabar">
        <div className="cs-metabar__item">
          <span className="cap">Client</span>
          <div>{isOrigami ? "Origami Sushi Atelier" : "Private client"}</div>
        </div>
        <div className="cs-metabar__item">
          <span className="cap">Sector</span>
          <div>{project.sector}</div>
        </div>
        <div className="cs-metabar__item">
          <span className="cap">Location</span>
          <div>{project.location}</div>
        </div>
        <div className="cs-metabar__item">
          <span className="cap">Year</span>
          <div>{project.year}</div>
        </div>
        <div className="cs-metabar__item">
          <span className="cap">Scope</span>
          <div>{isOrigami ? "Interior architecture, joinery, lighting" : "Interior architecture"}</div>
        </div>
        <div className="cs-metabar__item">
          <span className="cap">Area</span>
          <div>{isOrigami ? "3 venues · 420—780 m²" : "—"}</div>
        </div>
      </div>

      {/* NARRATIVE */}
      <section className="cs-narrative">
        <div>
          <p className="eyebrow">Brief</p>
          <h2 className="h-section cs-narrative__h" style={{ marginTop: 18 }}>
            A sushi atelier<br/><em>told</em> as a ritual<br/>of folded paper.
          </h2>
          {project.award && (
            <p className="cap" style={{ marginTop: 28 }}>{project.award}</p>
          )}
        </div>
        <div className="cs-narrative__body">
          {isOrigami ? (
            <>
              <p>
                Origami arrived as an unusual brief: not a restaurant, but a
                three-act atelier — Jumeirah, Dubai Mall and Marsa Al Bateen —
                that had to feel of one hand while answering three very
                different rooms. The client asked for a place where the food's
                quiet precision could be felt before a single dish arrived at
                the counter.
              </p>
              <p>
                We worked with paper as the central metaphor. Folded walls,
                vertical timber screens and recessed light coves do the
                spatial work; mirror polish, blackened steel and chestnut
                veneer carry the material vocabulary. Lighting is electric and
                low — a thin warm seam between volumes — so that what the
                guest sees first is the chef's hands, not the room.
              </p>
              <p>
                Across all three venues we held one rule: every visible
                hinge, ceiling shadow line and floor seam had to draw a
                vertical or a horizontal — never a curve. The curves were
                reserved for the food.
              </p>
            </>
          ) : (
            <>
              <p>
                {project.blurb || "A private commission delivered by the studio."}
                The full case study narrative is written in collaboration with
                the client and the architectural photographer, then published
                with credits.
              </p>
              <p style={{ color: "var(--muted)" }}>
                Per-project narrative, plans, material schedules and process
                photographs are being prepared with the client. This page
                shows the photographic record only.
              </p>
            </>
          )}
        </div>
      </section>

      {/* PULL QUOTE */}
      <section className="cs-pullquote">
        <blockquote>
          {isOrigami
            ? <>"The curves were <em>reserved</em><br/>for the food."</>
            : <>"Modesty with <em>elegance</em>,<br/>calm with luxury."</>}
        </blockquote>
        <p className="cap">{isOrigami ? "From the design statement" : "Studio principle, 2007—"}</p>
      </section>

      {/* GALLERY */}
      <section className="cs-gallery">
        {galleryFour.map((src, k) => (
          <figure
            key={k}
            className={"cs-g--0" + (k + 1)}
            onClick={() => setLightbox({ src, caption: project.name + " · Plate " + String(k + 1).padStart(2, "0") })}
          >
            <div className="frame"><img src={src} alt={project.name + " — image " + (k + 1)} loading="lazy" /></div>
            <figcaption>
              <span>{isOrigami
                ? ["Jumeirah", "Dubai Mall", "Marsa Al Bateen", "Detail"][k]
                : "Plate " + String(k + 1).padStart(2, "0")}</span>
              <span className="num">{String(k + 1).padStart(2, "0")} / 04</span>
            </figcaption>
          </figure>
        ))}
      </section>

      {/* CREDITS */}
      <div className="cs-credits">
        <div>
          <span className="cap">Interior Architecture</span>
          <div>VSHD Design</div>
        </div>
        <div>
          <span className="cap">Photography</span>
          <div>To be credited<br/><span style={{ color: "var(--muted)", fontSize: 11, letterSpacing: ".06em" }}>Confirm photographer + licence</span></div>
        </div>
        <div>
          <span className="cap">Press</span>
          <div>{isOrigami ? "Dezeen, 2022" : "—"}</div>
        </div>
        <div>
          <span className="cap">Year</span>
          <div>{project.year}</div>
        </div>
      </div>

      {/* NEXT / PREV */}
      <nav className="cs-nextprev" aria-label="Project navigation">
        <a onClick={() => go("project/" + prev.slug)}>
          <span className="cap">← Previous</span>
          <span className="name">{prev.name.split(" · ")[0]}<em style={{ color: "var(--muted)", fontSize: 14, marginLeft: 8 }}>{prev.sector}</em></span>
        </a>
        <a onClick={() => go("project/" + next.slug)} style={{ textAlign: "right" }}>
          <span className="cap">Next →</span>
          <span className="name">{next.name.split(" · ")[0]}<em style={{ color: "var(--muted)", fontSize: 14, marginLeft: 8 }}>{next.sector}</em></span>
        </a>
      </nav>

      {/* CTA */}
      <section className="section">
        <div className="cta-band">
          <div>
            <p className="eyebrow">Begin</p>
            <h2 className="h-section" style={{ marginTop: 18, maxWidth: 20 + "ch" }}>
              A similar brief? <em>Tell us.</em>
            </h2>
          </div>
          <button className="btn btn--solid" onClick={onOpenEnquiry}>
            Start a project <span className="arrow" />
          </button>
        </div>
      </section>

      <Footer onOpenEnquiry={onOpenEnquiry} go={go} />

      <Lightbox
        src={lightbox && lightbox.src}
        caption={lightbox && lightbox.caption}
        onClose={() => setLightbox(null)}
      />
    </div>
  );
}

/* ================= Stub pages (Studio, Awards, etc) ================= */
function Stub({ title, eyebrow, go, onOpenEnquiry }) {
  return (
    <div data-screen-label={"Stub · " + title}>
      <header className="page-head">
        <div>
          <p className="eyebrow">{eyebrow}</p>
          <h1 className="h-display" style={{ marginTop: 18 }}>{title}</h1>
        </div>
        <div>
          <p className="lede">
            This page is part of the full IA (10 routes) but isn't built in this
            prototype pass. The Home, Projects index and one full Case Study
            (Origami) carry the design system.
          </p>
          <div style={{ marginTop: 24, display: "flex", gap: 12, flexWrap: "wrap" }}>
            <button className="btn" onClick={() => go("")}>← Home</button>
            <button className="btn" onClick={() => go("projects")}>Projects index</button>
            <button className="btn" onClick={() => go("project/origami")}>Case study</button>
          </div>
        </div>
      </header>
      <Footer onOpenEnquiry={onOpenEnquiry} go={go} />
    </div>
  );
}

Object.assign(window, { Home, Projects, CaseStudy, Stub });
