/* PIXYcal — "Poznáváte se v tomhle?" pain-point carousel
   Smooth fan-stack animation, click any visible card to bring it front.
   Uses shared primitives from window (set by app.jsx). */

const { useState: useStateP, useEffect: useEffectP, useRef: useRefP, useCallback: useCallbackP } = React;

/* ── icons local to this file ─────────────────────────────────────────────── */
function PIcon({ name, size = 20 }) {
  const paths = {
    mail:      <><rect x="3" y="5" width="18" height="14"/><path d="m3 7 9 6 9-6"/></>,
    cart:      <><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/></>,
    target:    <><circle cx="12" cy="12" r="9"/><circle cx="12" cy="12" r="5"/><circle cx="12" cy="12" r="1.6" fill="currentColor" stroke="none"/></>,
    sparkles:  <><path d="M12 3v6M9 6h6M5 13l1 3 3 1-3 1-1 3-1-3-3-1 3-1zM17 13l.7 2 2 .7-2 .7-.7 2-.7-2-2-.7 2-.7z"/></>,
    megaphone: <><path d="M4 9v6h3l9 5V4L7 9Z"/><path d="M18 9a4 4 0 0 1 0 6"/></>,
    chevL:     <><path d="m15 18-6-6 6-6"/></>,
    chevR:     <><path d="m9 18 6-6-6-6"/></>,
  };
  const p = paths[name]; if (!p) return null;
  return (
    <svg viewBox="0 0 24 24" width={size} height={size} fill="none"
         stroke="currentColor" strokeWidth={1.7} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      {p}
    </svg>
  );
}

/* ── data ─────────────────────────────────────────────────────────────────── */
const PAIN_CARDS = [
  { id: "poptavky", icon: "mail",      label: "Poptávky bez reakce",   quote: `„Poptávky z formulářů leží dny v systému, nikdo je neřeší, případně se ozve po pár dnech a zákazník nakoupí jinde."` },
  { id: "kosik",    icon: "cart",      label: "Opuštěné košíky",       quote: `„Lidi si projdou produkty, vyberou si, naházejí věci do košíku... a pak odejdou."` },
  { id: "reklama",  icon: "target",    label: "Reklama je labyrint",   quote: `„Ztrácím se v rozhraní Mety a nastavení kampaní mě děsí."` },
  { id: "obsah",    icon: "sparkles",  label: "Obsah žere čas",        quote: `„Tvorba obsahu a vymýšlení příspěvků mi bere všechen čas."` },
  { id: "databaze", icon: "mail",      label: "Databáze leží ladem",   quote: `„Naše e-mailová databáze leží ladem a nikdo s ní nepracuje."` },
  { id: "lajky",    icon: "megaphone", label: "Lajky bez objednávek",  quote: `„Příspěvky sice mají lajky, ale nepřináší nám žádné objednávky."` },
];

const N = PAIN_CARDS.length;

/* slot definitions: distance from active → visual transform */
const SLOT = {
   0: { x:    0, y: -68, rot:  0,    z: 20, op: 1,    pointer: "auto",  scale: 1    },
   1: { x:  250, y:  14, rot:  3,    z: 10, op: 0.72, pointer: "auto",  scale: 0.97 },
   2: { x:  480, y: -14, rot: -2.5,  z:  1, op: 0,    pointer: "none",  scale: 0.94 },
  "-1":{ x: -250, y:  14, rot: -3,   z: 10, op: 0.72, pointer: "auto",  scale: 0.97 },
  "-2":{ x: -480, y: -14, rot:  2.5, z:  1, op: 0,    pointer: "none",  scale: 0.94 },
};

function getSlot(activeIdx, cardIdx) {
  let d = ((cardIdx - activeIdx) % N + N) % N;   // 0..N-1
  if (d > N / 2) d -= N;                          // fold to -(N/2)..N/2
  return SLOT[d] || SLOT[2];                      // default to hidden far-right
}

/* ── single card ─────────────────────────────────────────────────────────── */
function PainCard({ card, slot, isActive, onClick }) {
  const t = `translate(-50%, -50%) translateX(${slot.x}px) translateY(${slot.y}px) rotate(${slot.rot}deg) scale(${slot.scale})`;
  return (
    <button
      type="button"
      aria-label={card.label}
      aria-current={isActive || undefined}
      tabIndex={slot.pointer === "none" ? -1 : 0}
      onClick={onClick}
      style={{
        position: "absolute", left: "50%", top: "50%",
        width: 340, padding: "26px 26px 30px",
        textAlign: "left", cursor: "pointer",
        border: `1px solid ${isActive ? "var(--px-accent-a)" : "var(--px-line-strong)"}`,
        background: isActive ? "var(--px-gradient)" : "var(--px-surface-2)",
        color: isActive ? "#fff" : "var(--px-text-muted)",
        zIndex: slot.z, opacity: slot.op,
        pointerEvents: slot.pointer,
        boxShadow: isActive
          ? "0 12px 0 var(--px-surface-3), var(--px-glow-strong)"
          : "none",
        transform: t,
        transition: "transform 520ms cubic-bezier(0.16,1,0.3,1), opacity 520ms cubic-bezier(0.16,1,0.3,1), background 520ms cubic-bezier(0.16,1,0.3,1), border-color 520ms cubic-bezier(0.16,1,0.3,1), box-shadow 520ms cubic-bezier(0.16,1,0.3,1)",
        display: "flex", flexDirection: "column",
        borderRadius: "var(--px-radius)",
        outline: "none",
      }}
    >
      {/* icon */}
      <span style={{
        marginBottom: 14, flexShrink: 0,
        display: "inline-flex", alignItems: "center", justifyContent: "center",
        width: 44, height: 44,
        border: `1px solid ${isActive ? "rgba(255,255,255,0.25)" : "var(--px-line)"}`,
        background: isActive ? "rgba(255,255,255,0.18)" : "var(--px-surface-1)",
        color: isActive ? "#fff" : "var(--px-accent-a)",
        borderRadius: "var(--px-radius)",
        transition: "background 520ms, border-color 520ms, color 520ms",
      }}>
        <PIcon name={card.icon} size={20} />
      </span>
      {/* label */}
      <span style={{
        display: "block", flexShrink: 0,
        fontFamily: "var(--px-font-mono)", fontWeight: 700, fontSize: 10,
        letterSpacing: "0.14em", textTransform: "uppercase",
        color: isActive ? "rgba(255,255,255,0.7)" : "var(--px-accent-a)",
        transition: "color 520ms",
      }}>{card.label}</span>
      {/* quote */}
      <p style={{
        margin: "10px 0 0",
        fontFamily: "var(--px-font-display)", fontWeight: 700,
        fontSize: 18, lineHeight: 1.32, letterSpacing: "-0.02em",
        color: isActive ? "#fff" : "var(--px-text-strong)",
        transition: "color 520ms",
        textWrap: "balance",
      }}>
        {card.quote}
      </p>
    </button>
  );
}

/* ── dot indicators ──────────────────────────────────────────────────────── */
function Dots({ count, active, onGo }) {
  return (
    <div style={{ display: "flex", gap: 8, justifyContent: "center", alignItems: "center" }}>
      {Array.from({ length: count }, (_, i) => (
        <button key={i} type="button" aria-label={`Karta ${i + 1}`} onClick={() => onGo(i)}
          style={{
            width: i === active ? 24 : 8, height: 8, padding: 0, border: "none", cursor: "pointer",
            background: i === active ? "var(--px-gradient)" : "var(--px-line-strong)",
            borderRadius: "var(--px-radius)",
            transition: "width 250ms var(--px-easing), background 250ms",
          }} />
      ))}
    </div>
  );
}

/* ── main section ─────────────────────────────────────────────────────────── */
function PainSection({ t: tweaks }) {
  const [active, setActive] = useStateP(0);
  const timerRef = useRefP(null);

  const go = useCallbackP((idx) => {
    setActive(((idx % N) + N) % N);
  }, []);

  const prev = () => go(active - 1);
  const next = () => go(active + 1);

  /* auto-advance */
  useEffectP(() => {
    timerRef.current = setInterval(() => setActive((a) => (a + 1) % N), 4800);
    return () => clearInterval(timerRef.current);
  }, []);

  /* reset timer on manual pick */
  const pick = (idx) => {
    clearInterval(timerRef.current);
    go(idx);
    timerRef.current = setInterval(() => setActive((a) => (a + 1) % N), 4800);
  };

  /* keyboard */
  useEffectP(() => {
    const onKey = (e) => {
      if (e.key === "ArrowRight") pick(active + 1);
      if (e.key === "ArrowLeft")  pick(active - 1);
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [active]);

  const Reveal = window.Reveal;
  const Eyebrow = window.Eyebrow;

  return (
    <section id="pripady" style={{
      paddingBlock: "calc(112px * var(--px-density))",
      borderBottom: "1px solid var(--px-line)",
      background: "var(--px-surface-1)",
    }}>
      <div className="px-container">
        {/* header */}
        {Reveal && Eyebrow ? (
          <Reveal style={{ textAlign: "center", maxWidth: 720, marginInline: "auto", marginBottom: 64 }}>

            <h2 style={{
              margin: "16px 0 14px",
              fontFamily: "var(--px-font-display)", fontWeight: 700,
              fontSize: "clamp(32px, 4.4vw, 56px)", lineHeight: 1.02,
              letterSpacing: "-0.04em", color: "var(--px-text-strong)", textWrap: "balance",
            }}>
              {tweaks?.painHeadline || "Poznáváte se"}{" "}
              <span style={{ background: "var(--px-gradient)", WebkitBackgroundClip: "text", WebkitTextFillColor: "transparent" }}>
                {tweaks?.painAccent || "v tomhle?"}
              </span>
            </h2>
            <p style={{ margin: 0, fontSize: 17, lineHeight: 1.55, color: "var(--px-text-muted)" }}>
              {tweaks?.painSubtitle || "Tyhle situace řešíme každý den. Možná i vy."}
            </p>
          </Reveal>
        ) : null}

        {/* carousel */}
        <div style={{
          position: "relative", marginInline: "auto", maxWidth: 900,
          border: "1px solid var(--px-line)", background: "var(--px-surface-0)",
          borderRadius: "var(--px-radius)", overflow: "hidden",
          minHeight: 420,
        }}>
          {/* dot-grid bg */}
          <svg aria-hidden="true" style={{
            position: "absolute", inset: 0, width: "100%", height: "100%",
            opacity: 0.18, pointerEvents: "none",
            maskImage: "radial-gradient(70% 80%, black 40%, transparent 100%)",
            WebkitMaskImage: "radial-gradient(70% 80%, black 40%, transparent 100%)",
          }}>
            <defs>
              <pattern id="px-pain-dots" x="0" y="0" width="13" height="13" patternUnits="userSpaceOnUse">
                <circle cx="1" cy="1" r="0.9" fill="var(--px-text-strong)" />
              </pattern>
            </defs>
            <rect width="100%" height="100%" fill="url(#px-pain-dots)" />
          </svg>

          {/* radial glow behind active */}
          <div aria-hidden style={{
            position: "absolute", top: "30%", left: "50%", transform: "translate(-50%,-50%)",
            width: 500, height: 340, pointerEvents: "none",
            background: `radial-gradient(ellipse at center, rgba(var(--px-glow-rgb),0.14), transparent 70%)`,
            transition: "all 520ms",
          }} />

          {/* cards */}
          <div style={{ position: "relative", height: 340, marginTop: 40 }}>
            {PAIN_CARDS.map((card, i) => (
              <PainCard key={card.id} card={card}
                slot={getSlot(active, i)}
                isActive={i === active}
                onClick={() => pick(i)} />
            ))}
          </div>

          {/* nav + dots */}
          <div style={{
            position: "relative", zIndex: 30, paddingBlock: "20px 28px",
            display: "flex", alignItems: "center", justifyContent: "center", gap: 16,
          }}>
            <button type="button" aria-label="Předchozí" onClick={prev}
              style={{
                width: 42, height: 42, display: "inline-flex", alignItems: "center", justifyContent: "center",
                background: "var(--px-surface-2)", border: "1px solid var(--px-line-strong)",
                color: "var(--px-text-strong)", cursor: "pointer",
                borderRadius: "var(--px-radius)", transition: "background 150ms",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--px-surface-3)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "var(--px-surface-2)"}>
              <PIcon name="chevL" size={18} />
            </button>

            <Dots count={N} active={active} onGo={pick} />

            <button type="button" aria-label="Další" onClick={next}
              style={{
                width: 42, height: 42, display: "inline-flex", alignItems: "center", justifyContent: "center",
                background: "var(--px-surface-2)", border: "1px solid var(--px-line-strong)",
                color: "var(--px-text-strong)", cursor: "pointer",
                borderRadius: "var(--px-radius)", transition: "background 150ms",
              }}
              onMouseEnter={(e) => e.currentTarget.style.background = "var(--px-surface-3)"}
              onMouseLeave={(e) => e.currentTarget.style.background = "var(--px-surface-2)"}>
              <PIcon name="chevR" size={18} />
            </button>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { PainSection });
