/* global React */
const { useState: useStateTh, useEffect: useEffectTh } = React;

const ALL_TECHNIQUES = [
  ["Vratna kičma", "Miofascijalno opuštanje vratne kičme", "Myofascial", "1 dan", "Mekotkivna tehnika za oslobađanje fascijalnih restrikcija cervikalnog regiona."],
  ["Vratna kičma", "Generalna mobilizacija vratne kičme", "Mobilizacija", "1 dan", "Ritmičke niskoamplitudne tehnike za povećanje opsega pokreta."],
  ["Vratna kičma", "O.A.A. C0-C1-C2 rotaciona manipulacija", "HVLA", "2 dana", "Precizna HVLA za gornji cervikalni region."],
  ["Vratna kičma", "Cradle / chin hold rotaciona manipulacija C2-C6", "HVLA", "2 dana", "Kontrolisana rotaciona manipulacija srednjeg cervikalnog regiona."],
  ["Torakalna", "CTJ manipulacija u proniranom položaju", "HVLA", "1 dan", "Manipulacija cervikotorakalnog prelaza."],
  ["Torakalna", "Generalne mobilizacije torakalne kičme", "Mobilizacija", "1 dan", "Osnovne mobilizacione tehnike torakalnog regiona."],
  ["Torakalna", "Classic DOG manipulacija torakalne kičme", "HVLA", "2 dana", "Klasična torakalna manipulacija i njene varijacije."],
  ["Torakalna", "Classic butterfly manipulacija torakalne kičme", "HVLA", "1 dan", "Butterfly varijanta torakalne manipulacije."],
  ["LS kičma", "Generalne mobilizacije LS kičme", "Mobilizacija", "1 dan", "Osnovne mobilizacije lumbosakralnog regiona."],
  ["LS kičma", "Londonska osteopatska tehnika za akutni disk", "Specijalna", "2 dana", "Specijalizovana tehnika za akutnu disk-patologiju."],
  ["LS kičma", "Lumbar Roll manipulacija", "HVLA", "2 dana", "Klasična lumbalna HVLA u bočnom položaju."],
  ["LS kičma", "Chicago Roll manipulacija", "HVLA", "2 dana", "Napredna varijanta sa prilagođenom mehanikom tela."],
  ["SI zglob", "Side Roll SI zglob manipulacija", "HVLA", "1 dan", "Stabilna kontrolisana tehnika za SI disfunkciju."],
  ["Visceralno", "Generalne visceralne osteopatske tehnike", "Visceralno", "2 dana", "Rad sa visceralnom pokretljivošću i fascijom."],
  ["Periferne", "Periferne mobilizacije i manipulacije", "Mobilizacija", "2 dana", "Perifeme zglobne tehnike — rame, kuk, koleno, skočni zglob."],
];

function TehnikePage() {
  const { isMobile, isTablet } = useBreakpoint();
  const bp = (d, t, m) => isMobile ? m : isTablet ? t : d;
  const [filter, setFilter] = useStateTh(() => {
    try { return localStorage.getItem("omt-spine-region") || "Sve"; } catch { return "Sve"; }
  });
  const [q, setQ] = useStateTh("");
  const [hover, setHover] = useStateTh(null);
  useEffectTh(() => { try { localStorage.removeItem("omt-spine-region"); } catch {} }, []);

  const heroRef   = useReveal(0.1);
  const atlasRef  = useReveal(0.1);
  const searchRef = useReveal(0.05);
  const [listKey, setListKey] = useStateTh("init");
  useEffectTh(() => { setListKey(filter + "||" + q); }, [filter, q]);

  const filters = ["Sve", "Vratna kičma", "Torakalna", "LS kičma", "SI zglob", "Visceralno", "Periferne"];
  const list = ALL_TECHNIQUES.filter(t =>
    (filter === "Sve" || t[0] === filter) &&
    (q === "" || t[1].toLowerCase().includes(q.toLowerCase()))
  );
  const tagColor = () => ({ bg: "rgba(4,175,143,.15)", fg: "#02604F" });

  return (
    <main>
      <section style={{ padding: bp("64px 32px 36px","48px 24px 28px","40px 20px 24px"), background: "linear-gradient(180deg,#F0FBF7 0%,#fff 100%)" }}>
        <div style={{ maxWidth: 1320, margin: "0 auto", textAlign: isMobile ? "center" : "left" }} ref={heroRef}>
          <div style={{ animation: "omt-fade-up 0.55s var(--ease-spring) both" }}>
            <Eyebrow>Spisak tehnika · Interaktivni atlas</Eyebrow>
          </div>
          <h1 style={{ margin: "14px 0 14px", fontSize: bp("clamp(32px,4vw,52px)","clamp(26px,5vw,38px)","clamp(22px,6vw,30px)"), lineHeight: 1.06, letterSpacing: "-0.028em", fontWeight: 800, textWrap: "balance", animation: "omt-fade-up 0.6s 0.08s var(--ease-spring) both" }}>
            15 tehnika. {!isMobile && "Kliknite region kičme."}
          </h1>
          <p style={{ fontSize: bp(17,15,14), lineHeight: 1.6, color: "var(--text-secondary)", maxWidth: 680, margin: 0, animation: "omt-fade-up 0.6s 0.16s var(--ease-spring) both" }}>
            Svaka tehnika se uvežbava kroz sve faze pokreta, u kontrolisanoj praksi,
            pre primene pune snage. {!isMobile && "Izaberite region da filtrirate listu."}
          </p>
        </div>
      </section>

      <section style={{ padding: bp("24px 32px 64px","16px 24px 48px","12px 20px 40px") }}>
        <div style={{ maxWidth: 1320, margin: "0 auto" }}>

          {/* Mobile: horizontal chip filter bar instead of atlas */}
          {isMobile && (
            <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16, animation: "omt-fade-up 0.5s 0.1s var(--ease-spring) both" }}>
              {filters.map(f => <Chip key={f} active={filter===f} onClick={() => setFilter(f)}>{f}</Chip>)}
            </div>
          )}

          <div style={{ display: "grid", gridTemplateColumns: isMobile ? "1fr" : isTablet ? "1fr" : "380px 1fr", gap: bp(48,0,0), alignItems: "flex-start" }}>

            {/* SpineAtlas: desktop only */}
            {!isMobile && (
              <div ref={atlasRef} style={{ position: isTablet ? "static" : "sticky", top: 100, animation: "omt-slide-r 0.65s 0.1s var(--ease-spring) both" }}>
                {isTablet && (
                  <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 20 }}>
                    {filters.map(f => <Chip key={f} active={filter===f} onClick={() => setFilter(f)}>{f}</Chip>)}
                  </div>
                )}
                {!isTablet && <SpineAtlas filter={filter} setFilter={setFilter} hover={hover} setHover={setHover}/>}
              </div>
            )}

            <div ref={searchRef}>
              {/* Search bar */}
              <div style={{
                background: "#fff", borderRadius: 999, padding: bp("6px 6px 6px 22px","6px 6px 6px 18px","6px 6px 6px 16px"),
                display: "flex", alignItems: "center", boxShadow: "var(--shadow-card)",
                marginBottom: 16, animation: "omt-fade-up 0.5s 0.2s var(--ease-spring) both",
              }}>
                <Icon name="search" size={18} />
                <input value={q} onChange={(e)=>setQ(e.target.value)}
                  placeholder={isMobile ? "Pretraži tehniku…" : "Pretražite tehniku (npr. HVLA, Lumbar Roll, C0-C1)"}
                  style={{ flex: 1, border: 0, outline: 0, padding: bp("12px 14px","10px 12px","8px 12px"), fontSize: bp(15,14,14), fontFamily: "inherit", background: "transparent" }} />
              </div>

              {/* Desktop filter chips (shown beside atlas) */}
              {!isMobile && !isTablet && (
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap", marginBottom: 24, animation: "omt-fade-up 0.5s 0.28s var(--ease-spring) both" }}>
                  {filters.map(f => <Chip key={f} active={filter===f} onClick={()=>setFilter(f)}>{f}</Chip>)}
                </div>
              )}

              <div style={{ display: "grid", gridTemplateColumns: bp("repeat(2,1fr)","repeat(2,1fr)","1fr"), gap: bp(18,14,12) }}>
                {list.map(([region, title, tag, dur, desc], i) => {
                  const c = tagColor(tag);
                  const delay = Math.min(i * 0.06, 0.48);
                  return (
                    <div key={listKey + i} style={{ animation: `omt-fade-up 0.45s ${delay}s var(--ease-spring) both` }}>
                      <Card padding={bp(22,18,16)} hoverable style={{ display: "flex", flexDirection: "column", height: "100%" }}>
                        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 12 }}>
                          <span style={{ background: c.bg, color: c.fg, padding: "4px 10px", borderRadius: 14, fontWeight: 700, fontSize: 11, letterSpacing: "0.04em", textTransform: "uppercase" }}>{tag}</span>
                          <span style={{ fontSize: 11, color: "var(--text-tertiary)", display: "inline-flex", alignItems: "center", gap: 5, fontWeight: 600, flexShrink: 0 }}><Icon name="clock" size={12} /> {dur}</span>
                        </div>
                        <h3 style={{ margin: "12px 0 8px", fontSize: bp(17,15,15), fontWeight: 700, letterSpacing: "-0.012em", lineHeight: 1.3 }}>{title}</h3>
                        <p style={{ margin: 0, fontSize: bp(13.5,13,13), lineHeight: 1.55, color: "var(--text-secondary)" }}>{desc}</p>
                        <div style={{ marginTop: 14, fontSize: 12, color: "var(--text-tertiary)", display: "inline-flex", alignItems: "center", gap: 6 }}>
                          <Icon name="mapPin" size={12}/> {region}
                        </div>
                      </Card>
                    </div>
                  );
                })}
                {list.length === 0 && (
                  <div style={{ gridColumn: "span 2", textAlign: "center", color: "var(--text-tertiary)", padding: 48, animation: "omt-fade-in 0.4s both" }}>
                    Nema rezultata za „{q}". Probajte drugi pojam.
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>
  );
}

function SpineAtlas({ filter, setFilter, hover, setHover }) {
  const regions = [
    { id: "Vratna kičma", label: "Vratna kičma (C1–C7)", y: 64, h: 80, count: 7 },
    { id: "Torakalna", label: "Torakalna (T1–T12)", y: 160, h: 160, count: 12 },
    { id: "LS kičma", label: "Lumbalna (L1–L5)", y: 336, h: 90, count: 5 },
    { id: "SI zglob", label: "SI zglob", y: 442, h: 44, count: 0 },
  ];
  const isActive = (id) => filter === id || hover === id;
  const techCount = (id) => ALL_TECHNIQUES.filter(t => t[0] === id).length;

  return (
    <div style={{
      background: "#fff", borderRadius: 24, padding: 28,
      boxShadow: "var(--shadow-card)",
    }}>
      <div style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.08em", textTransform: "uppercase", color: "var(--omt-green-ink)", marginBottom: 8 }}>
        Atlas kičme
      </div>
      <div style={{ fontSize: 15, fontWeight: 600, color: "var(--text-secondary)", marginBottom: 20 }}>
        Kliknite region za filter
      </div>
      <div style={{ position: "relative" }}>
        <svg viewBox="0 0 340 520" width="100%" style={{ display: "block" }}>
          <defs>
            <linearGradient id="spAtlas" x1="0" y1="0" x2="0" y2="1">
              <stop offset="0%" stopColor="#17A4B5"/>
              <stop offset="100%" stopColor="#04AF8F"/>
            </linearGradient>
          </defs>
          <g onClick={() => setFilter("Sve")} style={{cursor:"pointer"}}>
            <circle cx="150" cy="32" r="24" fill="#F2F4F3" stroke="var(--border-default)" strokeWidth="1.5"/>
            <circle cx="142" cy="28" r="2" fill="var(--text-tertiary)"/>
            <circle cx="158" cy="28" r="2" fill="var(--text-tertiary)"/>
            <path d="M 142 40 Q 150 44 158 40" stroke="var(--text-tertiary)" strokeWidth="1.5" fill="none"/>
          </g>
          {regions.map((r) => {
            const active = isActive(r.id);
            const step = r.count > 0 ? r.h / r.count : r.h;
            return (
              <g key={r.id}
                 onMouseEnter={() => setHover(r.id)}
                 onMouseLeave={() => setHover(null)}
                 onClick={() => setFilter(r.id)}
                 style={{ cursor: "pointer" }}>
                <rect x="90" y={r.y-6} width="120" height={r.h+12}
                      fill={active ? "rgba(4,175,143,0.10)" : "transparent"} rx="14"/>
                {r.count > 0 && Array.from({length: r.count}).map((_, i) => {
                  const yv = r.y + i*step + 1;
                  const wv = 40 + Math.sin(i*0.5)*2;
                  return (
                    <g key={i}>
                      <rect x={150 - wv/2} y={yv} width={wv} height={step-3}
                            rx="5" fill={active ? "url(#spAtlas)" : "#fff"}
                            stroke={active ? "rgba(4,175,143,0.4)" : "var(--border-default)"} strokeWidth="1.3"/>
                    </g>
                  );
                })}
                {r.count === 0 && (
                  <g>
                    <path d={`M 105 ${r.y+4} Q 150 ${r.y+r.h+18} 195 ${r.y+4}`}
                          stroke={active ? "url(#spAtlas)" : "var(--border-default)"}
                          strokeWidth="8" fill="none" strokeLinecap="round"/>
                  </g>
                )}
                <line x1="220" y1={r.y + r.h/2} x2="236" y2={r.y + r.h/2}
                      stroke={active ? "var(--omt-green-ink)" : "var(--border-default)"} strokeWidth="1.5"/>
                <text x="240" y={r.y + r.h/2 - 3} fontSize="12" fontWeight="700"
                      fill={active ? "var(--omt-green-ink)" : "var(--text-primary)"}>
                  {r.label.split(" ")[0]} {r.label.split(" ")[1] || ""}
                </text>
                <text x="240" y={r.y + r.h/2 + 12} fontSize="11" fontWeight="500"
                      fill="var(--text-tertiary)">
                  {techCount(r.id)} tehnika
                </text>
              </g>
            );
          })}
          <g onClick={() => setFilter("Sve")} style={{ cursor: "pointer" }}>
            <rect x="100" y="498" width="140" height="16" rx="8"
                  fill={filter === "Sve" ? "var(--omt-grad)" : "var(--surface-2)"}/>
            <text x="170" y="510" fontSize="10" fontWeight="700" textAnchor="middle"
                  fill={filter === "Sve" ? "#fff" : "var(--text-primary)"}
                  style={{ letterSpacing: "0.08em", textTransform: "uppercase" }}>
              Prikaži sve (15)
            </text>
          </g>
        </svg>
      </div>
    </div>
  );
}

window.TehnikePage = TehnikePage;
