/* === WORK — index (/work) + case detail (/work/:slug) === */

const { useState: wkState, useEffect: wkEffect } = React;

/* ----------------- INDEX ----------------- */
function WorkIndex() {
  const cases = window.SITE_DATA.work;
  const titleRef = window.useReveal("reveal");
  const [filter, setFilter] = wkState("all");
  const categories = useMemo(() => {
    const all = ["all", ...new Set(cases.map((c) => c.category))];
    return all;
  }, [cases]);

  const filtered = filter === "all" ? cases : cases.filter((c) => c.category === filter);

  return (
    <>
      {/* HERO */}
      <section style={{
        padding: "120px 32px 60px",
        background: "#f8f7f4",
        position: "relative",
        overflow: "hidden",
      }}>
        <window.AnimatedBlob size={620} gradient="linear-gradient(135deg, #0a6ef5, #05b89c)" style={{ top: "-20%", right: "-10%" }} opacity={0.14} />
        <window.AnimatedBlob size={420} gradient="linear-gradient(135deg, #e85d00, #f5a623)" style={{ bottom: "-25%", left: "-5%" }} opacity={0.10} />
        <div className="grid-bg" style={{ position: "absolute", inset: 0, opacity: 0.4, pointerEvents: "none" }} />

        <div ref={titleRef} style={{ maxWidth: 1680, margin: "0 auto", position: "relative" }}>
          <window.Breadcrumb items={[{ to: "/", label: "Главная" }, { label: "Продукты" }]} />
          <window.SectionTag>Наши продукты</window.SectionTag>
          <h1 style={{
            fontFamily: "Syne, sans-serif",
            fontSize: "clamp(44px, 5.6vw, 100px)",
            fontWeight: 800,
            color: "#0d0d0d",
            letterSpacing: "-0.035em",
            lineHeight: 0.98,
            marginTop: 24,
            marginBottom: 28,
            maxWidth: 1000,
          }}>
            Продукты, которые<br />
            <span className="text-gradient-blue">определяют стандарт</span>
          </h1>
          <p style={{
            fontFamily: "Inter, sans-serif",
            fontSize: "clamp(16px, 1.25vw, 19px)",
            lineHeight: 1.7, color: "#3a3a3a", maxWidth: 720,
            marginBottom: 48,
          }}>
            Наши продукты — каждый со своими измеримыми результатами.
            Продукты под соглашением о неразглашении доступны после подписания взаимного NDA.
          </p>

          {/* Category filter */}
          <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
            {categories.map((c) => {
              const active = filter === c;
              return (
                <button
                  key={c}
                  onClick={() => setFilter(c)}
                  style={{
                    padding: "10px 20px",
                    borderRadius: 100,
                    border: active ? "none" : "1px solid rgba(0,0,0,0.12)",
                    background: active ? "#0d0d0d" : "transparent",
                    color: active ? "#fff" : "#3a3a3a",
                    fontSize: 13, fontWeight: 500,
                    letterSpacing: "0.02em",
                    cursor: "pointer",
                    transition: "all 0.2s ease",
                  }}
                >
                  {c === "all" ? "Все" : c}
                </button>
              );
            })}
          </div>
        </div>
      </section>

      {/* GRID */}
      <section style={{ padding: "20px 32px 100px", background: "#f8f7f4" }}>
        <div style={{ maxWidth: 1680, margin: "0 auto" }}>
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(380px, 1fr))",
            gap: 28,
          }}>
            {filtered.map((c, i) => <WorkCard key={c.slug} c={c} index={i} />)}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: "40px 32px 100px", background: "#f8f7f4" }}>
        <div style={{
          maxWidth: 1320, margin: "0 auto",
          padding: "56px 52px",
          borderRadius: 28,
          background: "linear-gradient(135deg, #0a6ef5 0%, #0552c7 100%)",
          color: "#fff",
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 32,
          position: "relative",
          overflow: "hidden",
        }}>
          <window.AnimatedBlob size={400} gradient="linear-gradient(135deg, #05b89c, #0a6ef5)" style={{ top: "-30%", right: "-10%" }} opacity={0.45} />
          <div style={{ position: "relative", maxWidth: 560 }}>
            <h3 style={{
              fontFamily: "Syne, sans-serif",
              fontSize: "clamp(26px, 3.2vw, 38px)",
              fontWeight: 800,
              letterSpacing: "-0.025em",
              lineHeight: 1.1,
            }}>
              Заинтересовал один из продуктов?
            </h3>
            <p style={{
              fontFamily: "Inter, sans-serif",
              fontSize: 15, lineHeight: 1.7,
              color: "rgba(255,255,255,0.8)", marginTop: 14, maxWidth: 480,
            }}>
              Расскажем больше о технических деталях и обсудим, как этот опыт
              применим к вашей задаче.
            </p>
          </div>
          <window.GradientBtn to="/contact" size="lg" style={{ background: "#fff", color: "#0a6ef5", boxShadow: "0 12px 36px rgba(0,0,0,0.18)" }}>
            <span style={{ color: "#0a6ef5", fontWeight: 600 }}>Связаться</span>
          </window.GradientBtn>
        </div>
      </section>
    </>
  );
}

function WorkCard({ c, index }) {
  const ref = window.useReveal("reveal", 80 * index);
  const [h, setH] = wkState(false);
  return (
    <div ref={ref}>
      <window.Tilt max={5} scale={1.01}>
        <window.Link to={`/work/${c.slug}`}>
          <div
            onMouseEnter={() => setH(true)}
            onMouseLeave={() => setH(false)}
            style={{
              background: "#fff",
              borderRadius: 28,
              overflow: "hidden",
              border: "1px solid rgba(0,0,0,0.06)",
              transition: "box-shadow 0.5s ease",
              boxShadow: h ? "0 40px 100px rgba(0,0,0,0.14)" : "0 4px 24px rgba(0,0,0,0.04)",
              cursor: "pointer",
            }}>
            <div style={{ position: "relative", height: 280, overflow: "hidden" }}>
              <img src={c.image} alt={window.tx(c.title)} style={{
                width: "100%", height: "100%", objectFit: "cover",
                transform: h ? "scale(1.08)" : "scale(1)",
                transition: "transform 0.8s cubic-bezier(0.16, 1, 0.3, 1)",
              }} />
              <div style={{
                position: "absolute", inset: 0,
                background: `linear-gradient(to bottom, transparent 40%, ${c.accent}dd 100%)`,
                opacity: h ? 0.85 : 0.55,
                transition: "opacity 0.4s ease",
              }} />
              <div style={{
                position: "absolute", top: 22, left: 24,
                fontSize: 11, fontWeight: 700, color: "rgba(255,255,255,0.85)",
                letterSpacing: "0.12em", textTransform: "uppercase",
              }}>
                {window.tx(c.category)}
              </div>
              <div style={{
                position: "absolute", bottom: 22, left: 24, right: 24,
                color: "#fff",
              }}>
                <div style={{ fontFamily: "Syne, sans-serif", fontSize: 30, fontWeight: 700, letterSpacing: "-0.025em", lineHeight: 1.1 }}>
                  <span className="title-anim">{window.tx(c.title)}</span>
                </div>
                <div style={{ fontSize: 13, color: "rgba(255,255,255,0.85)", marginTop: 6 }}>
                  {window.tx(c.subtitle)}
                </div>
              </div>
            </div>
            <div style={{ padding: "28px 30px" }}>
              <p style={{
                fontFamily: "Inter, sans-serif",
                fontSize: 14, lineHeight: 1.7, color: "#5a5a5a",
                marginBottom: 18,
              }}>
                {window.tx(c.shortDesc)}
              </p>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 14 }}>
                {c.tags.map((t, ti) => <window.Tag key={(typeof t === "string" ? t : (t.ru || t.en)) + "-" + ti} accent={c.accent}>{t}</window.Tag>)}
              </div>
              <span className="link-anim" style={{
                fontSize: 13, fontWeight: 600, color: c.accent,
                fontFamily: "Inter, sans-serif",
              }}>
                Открыть кейс <window.I.ArrowUpRight size={13} color={c.accent} />
              </span>
            </div>
          </div>
        </window.Link>
      </window.Tilt>
    </div>
  );
}

/* ----------------- DETAIL ----------------- */
function WorkDetail({ slug }) {
  const c = window.SITE_DATA.work.find((x) => x.slug === slug);
  if (!c) return <window.NotFoundPage label="Продукт не найден" backTo="/work" backLabel="Все продукты" />;

  const titleRef = window.useReveal("reveal");
  const related = window.SITE_DATA.work.filter((x) => x.slug !== slug).slice(0, 2);

  return (
    <>
      {/* HERO */}
      <section style={{ background: "#f8f7f4", paddingTop: 140 }}>
        <div style={{ maxWidth: 1680, margin: "0 auto", padding: "0 32px 60px" }}>
          <window.Breadcrumb items={[
            { to: "/", label: "Главная" },
            { to: "/work", label: "Продукты" },
            { label: c.title },
          ]} />
          <div ref={titleRef} style={{
            display: "grid",
            gridTemplateColumns: "1.4fr 1fr",
            gap: 60, alignItems: "end",
            paddingBottom: 60,
          }} className="case-hero">
            <div>
              <div style={{
                display: "inline-flex", alignItems: "center", gap: 10,
                padding: "6px 14px",
                background: `${c.accent}10`,
                border: `1px solid ${c.accent}30`,
                borderRadius: 100,
                marginBottom: 28,
                fontSize: 11, fontWeight: 700,
                letterSpacing: "0.12em", textTransform: "uppercase",
                color: c.accent,
              }}>
                <span style={{ width: 6, height: 6, borderRadius: "50%", background: c.accent }} />
                Case study · {window.tx(c.category)}
              </div>
              <h1 style={{
                fontFamily: "Syne, sans-serif",
                fontSize: "clamp(56px, 8vw, 116px)",
                fontWeight: 800,
                color: "#0d0d0d",
                letterSpacing: "-0.04em",
                lineHeight: 0.96,
                marginBottom: 22,
              }}>
                {window.tx(c.title)}
              </h1>
              <p style={{
                fontFamily: "Syne, sans-serif",
                fontSize: "clamp(20px, 2.2vw, 28px)",
                fontWeight: 500,
                color: "#3a3a3a",
                letterSpacing: "-0.015em",
                lineHeight: 1.25,
                maxWidth: 700, marginBottom: 32,
              }}>
                {window.tx(c.subtitle)}
              </p>
              <div style={{ display: "flex", flexWrap: "wrap", gap: 8 }}>
                {c.tags.map((t, ti) => <window.Tag key={(typeof t === "string" ? t : (t.ru || t.en)) + "-" + ti} accent={c.accent}>{t}</window.Tag>)}
              </div>
            </div>

            {/* meta card */}
            <aside style={{
              background: "#fff",
              border: "1px solid rgba(0,0,0,0.06)",
              borderRadius: 24,
              padding: 28,
              boxShadow: "0 16px 60px rgba(0,0,0,0.06)",
            }}>
              <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.12em", textTransform: "uppercase", color: c.accent, marginBottom: 18 }}>
                О продукте
              </div>
              {[
                ["Клиент", c.client],
                ["Регион", c.region],
                ["Год",    c.year],
                ["Категория", c.category],
              ].map(([k, v], i) => (
                <div key={k} style={{
                  display: "flex", justifyContent: "space-between", gap: 16,
                  padding: "12px 0",
                  borderTop: i === 0 ? "none" : "1px solid rgba(0,0,0,0.06)",
                  fontSize: 13,
                }}>
                  <span style={{ color: "#7a7a7a" }}>{k}</span>
                  <span style={{ color: "#0d0d0d", fontWeight: 600, textAlign: "right", maxWidth: 220 }}>{v}</span>
                </div>
              ))}
            </aside>
          </div>
        </div>

        {/* Big image */}
        <div style={{
          maxWidth: 1680, margin: "0 auto", padding: "0 32px",
        }}>
          <window.Tilt max={3} scale={1}>
            <div style={{
              borderRadius: 32,
              overflow: "hidden",
              boxShadow: `0 40px 100px ${c.accent}30`,
              border: "1px solid rgba(0,0,0,0.06)",
              position: "relative",
            }}>
              <img src={c.image} alt={window.tx(c.title)} style={{
                width: "100%", height: 540, objectFit: "cover", display: "block",
              }} />
              <div style={{
                position: "absolute", inset: 0,
                background: `linear-gradient(135deg, ${c.accent}10, transparent 50%)`,
              }} />
            </div>
          </window.Tilt>
        </div>
        <style>{`@media (max-width: 980px){ .case-hero{ grid-template-columns: 1fr !important; }}`}</style>
      </section>

      {/* METRICS BAR */}
      <section style={{
        background: `linear-gradient(135deg, ${c.accent} 0%, ${c.accent}cc 100%)`,
        color: "#fff",
        padding: "60px 32px",
        position: "relative",
        overflow: "hidden",
        marginTop: 80,
      }}>
        <div style={{
          position: "absolute",
          top: "-20%", right: "-5%",
          width: 500, height: 500, borderRadius: "50%",
          background: "radial-gradient(circle, rgba(255,255,255,0.08), transparent 70%)",
        }} />
        <div style={{ maxWidth: 1680, margin: "0 auto", position: "relative" }}>
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(200px, 1fr))",
            gap: 24,
          }}>
            {c.metrics.map((m, i) => (
              <div key={i} style={{
                padding: "20px 24px",
                background: "rgba(255,255,255,0.08)",
                border: "1px solid rgba(255,255,255,0.18)",
                borderRadius: 16,
                backdropFilter: "blur(8px)",
              }}>
                <div style={{
                  fontFamily: "Inter, sans-serif",
                  fontSize: 28, fontWeight: 700,
                  letterSpacing: "-0.02em",
                  fontVariantNumeric: "tabular-nums",
                  lineHeight: 1,
                  marginBottom: 10,
                }}>
                  <window.AnimatedNum value={m.v} />
                </div>
                <div style={{ fontSize: 12, color: "rgba(255,255,255,0.78)", lineHeight: 1.4 }}>{m.l}</div>
              </div>
            ))}
          </div>
        </div>
      </section>

      {/* CHALLENGE / SOLUTION */}
      <section style={{ padding: "80px 32px", background: "#f8f7f4", position: "relative" }}>
        <window.FloatingShape kind="diamond" size={60} color={c.accent} style={{ top: 60, right: "10%", opacity: 0.12 }} speed={24} />
        <div style={{ maxWidth: 1320, margin: "0 auto" }}>
          <div style={{ marginBottom: 80 }}>
            <window.SectionTag tone="warm">Задача</window.SectionTag>
            <h2 style={{
              fontFamily: "Syne, sans-serif",
              fontSize: "clamp(28px, 3.6vw, 44px)",
              fontWeight: 800,
              color: "#0d0d0d",
              letterSpacing: "-0.025em",
              lineHeight: 1.1,
              marginTop: 24,
              marginBottom: 24,
            }}>
              С чем пришёл клиент
            </h2>
            <p style={{
              fontFamily: "Inter, sans-serif",
              fontSize: 17, lineHeight: 1.8, color: "#3a3a3a",
              maxWidth: 820,
            }}>
              {window.tx(c.challenge)}
            </p>
          </div>

          <div>
            <window.SectionTag tone="teal">Решение</window.SectionTag>
            <h2 style={{
              fontFamily: "Syne, sans-serif",
              fontSize: "clamp(28px, 3.6vw, 44px)",
              fontWeight: 800,
              color: "#0d0d0d",
              letterSpacing: "-0.025em",
              lineHeight: 1.1,
              marginTop: 24,
              marginBottom: 24,
            }}>
              Что мы построили
            </h2>
            <p style={{
              fontFamily: "Inter, sans-serif",
              fontSize: 17, lineHeight: 1.8, color: "#3a3a3a",
              maxWidth: 820,
            }}>
              {window.tx(c.solution)}
            </p>
          </div>
        </div>
      </section>

      {/* TESTIMONIAL */}
      {c.testimonial && (() => {
        const tst = c.testimonial;
        const initials = (tst.author || "?")
          .split(/\s+/).filter(Boolean).slice(0, 2)
          .map((w) => w[0].toUpperCase()).join("") || "?";
        return (
          <section style={{ padding: "80px 32px", background: "#f0ede8" }}>
            <div style={{ maxWidth: 1320, margin: "0 auto" }}>
              <div style={{
                padding: "60px 52px",
                background: "linear-gradient(135deg, #0d0d0d 0%, #1d1d1d 100%)",
                color: "#fff",
                borderRadius: 28,
                position: "relative",
                overflow: "hidden",
              }}>
                <window.AnimatedBlob size={400} gradient={`linear-gradient(135deg, ${c.accent}, #0a6ef5)`} style={{ top: "-30%", right: "-10%" }} opacity={0.3} />
                <div style={{ position: "relative" }}>
                  <div style={{
                    fontFamily: "Syne, sans-serif", fontSize: 90, fontWeight: 800,
                    color: `${c.accent}66`, lineHeight: 0.5, marginBottom: 0,
                  }}>"</div>
                  <p style={{
                    fontFamily: "Syne, sans-serif",
                    fontSize: "clamp(22px, 2.6vw, 32px)",
                    fontWeight: 500,
                    lineHeight: 1.35,
                    color: "#fff",
                    letterSpacing: "-0.015em",
                    marginBottom: 32,
                    maxWidth: 860,
                  }}>
                    «{window.tx(tst.quote)}»
                  </p>
                  <div style={{ display: "flex", alignItems: "center", gap: 14, paddingTop: 24, borderTop: "1px solid rgba(255,255,255,0.1)" }}>
                    {tst.avatar ? (
                      <img
                        src={tst.avatar}
                        alt={tst.author || ""}
                        width={48}
                        height={48}
                        loading="lazy"
                        onError={(e) => { e.currentTarget.style.display = "none"; e.currentTarget.nextSibling.style.display = "flex"; }}
                        style={{
                          width: 48, height: 48, borderRadius: "50%",
                          objectFit: "cover",
                          border: `1.5px solid ${c.accent}88`,
                          flexShrink: 0,
                        }}
                      />
                    ) : null}
                    <div style={{
                      width: 48, height: 48, borderRadius: "50%",
                      background: `linear-gradient(135deg, ${c.accent}, #0a6ef5)`,
                      display: tst.avatar ? "none" : "flex",
                      alignItems: "center", justifyContent: "center",
                      fontFamily: "Syne, sans-serif",
                      fontSize: 15, fontWeight: 800, color: "#fff",
                      letterSpacing: "0.02em",
                      flexShrink: 0,
                    }}>{initials}</div>
                    <div>
                      <div style={{ fontSize: 14, fontWeight: 700 }}>{tst.author}</div>
                      <div style={{ fontSize: 12, color: "rgba(255,255,255,0.6)" }}>{tst.role}</div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>
        );
      })()}

      {/* RELATED */}
      <section style={{ padding: "80px 32px", background: "#f8f7f4" }}>
        <div style={{ maxWidth: 1680, margin: "0 auto" }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "end", marginBottom: 40, flexWrap: "wrap", gap: 24 }}>
            <h2 style={{
              fontFamily: "Syne, sans-serif",
              fontSize: "clamp(28px, 3.6vw, 44px)",
              fontWeight: 800,
              color: "#0d0d0d",
              letterSpacing: "-0.025em",
              lineHeight: 1.05,
            }}>
              Другие продукты
            </h2>
            <window.Link to="/work" className="link-anim" style={{
              display: "inline-flex", alignItems: "center", gap: 8,
              fontSize: 14, fontWeight: 600, color: "#0a6ef5",
            }}>
              Все продукты <window.I.ArrowUpRight size={14} color="#0a6ef5" />
            </window.Link>
          </div>
          <div style={{
            display: "grid",
            gridTemplateColumns: "repeat(auto-fit, minmax(380px, 1fr))",
            gap: 24,
          }}>
            {related.map((rc) => <WorkCard key={rc.slug} c={rc} index={0} />)}
          </div>
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: "40px 32px 100px", background: "#f8f7f4" }}>
        <div style={{
          maxWidth: 1320, margin: "0 auto",
          padding: "56px 52px",
          borderRadius: 28,
          background: `linear-gradient(135deg, ${c.accent} 0%, ${c.accent}cc 100%)`,
          color: "#fff",
          display: "flex",
          flexWrap: "wrap",
          justifyContent: "space-between",
          alignItems: "center",
          gap: 32,
          position: "relative",
          overflow: "hidden",
        }}>
          <window.AnimatedBlob size={400} gradient={`linear-gradient(135deg, #ffffff, ${c.accent})`} style={{ top: "-30%", right: "-10%" }} opacity={0.3} />
          <div style={{ position: "relative", maxWidth: 540 }}>
            <h3 style={{
              fontFamily: "Syne, sans-serif",
              fontSize: "clamp(26px, 3.2vw, 38px)",
              fontWeight: 800, letterSpacing: "-0.025em", lineHeight: 1.1,
            }}>
              Похожая задача? Обсудим.
            </h3>
          </div>
          <window.GradientBtn to="/contact" size="lg" style={{ background: "#fff", color: c.accent, boxShadow: "0 12px 36px rgba(0,0,0,0.18)" }}>
            <span style={{ color: c.accent, fontWeight: 600 }}>Связаться</span>
          </window.GradientBtn>
        </div>
      </section>
    </>
  );
}

function WorkPage({ slug }) {
  if (slug) return <WorkDetail slug={slug} />;
  return <WorkIndex />;
}
window.WorkPage = WorkPage;
