/* Shared UI primitives — Apple HIG controls. */
(function () {
  const { useState, useRef, useEffect, useLayoutEffect } = React;
  const Icon = window.Icon;

  /* ---- Segmented control with sliding thumb ---- */
  function Segmented({ options, value, onChange }) {
    const wrapRef = useRef(null);
    const [thumb, setThumb] = useState({ left: 0, width: 0 });
    useLayoutEffect(() => {
      const wrap = wrapRef.current;
      if (!wrap) return;
      const idx = options.findIndex((o) => o.value === value);
      const el = wrap.querySelectorAll(".seg")[idx];
      if (el) setThumb({ left: el.offsetLeft, width: el.offsetWidth });
    }, [value, options]);
    return (
      <div className="segmented" ref={wrapRef}>
        <div className="thumb" style={{ transform: `translateX(${thumb.left - 2}px)`, width: thumb.width }} />
        {options.map((o) => (
          <button key={o.value} className={"seg " + (o.value === value ? "" : "dim")}
            onClick={() => onChange(o.value)}>{o.label}</button>
        ))}
      </div>
    );
  }

  /* ---- Sort menu (popover) ---- */
  function SortMenu({ value, options, onChange }) {
    const [open, setOpen] = useState(false);
    const btnRef = useRef(null);
    const cur = options.find((o) => o.value === value);
    return (
      <div style={{ position: "relative" }}>
        <button className="menu-btn" ref={btnRef} onClick={() => setOpen((v) => !v)}>
          {cur ? cur.label : value}
          <Icon name="chevDown" size={14} weight={2.4} className="chev" />
        </button>
        {open && (
          <>
            <div className="menu-scrim" onClick={() => setOpen(false)} />
            <div className="popover" style={{ right: 0, top: "calc(100% + 6px)" }}>
              {options.map((o) => (
                <button key={o.value} className={"mrow " + (o.value === value ? "on" : "")}
                  onClick={() => { onChange(o.value); setOpen(false); }}>
                  <span>{o.label}</span>
                  <Icon name="check" size={16} weight={2.4} className="check" />
                </button>
              ))}
            </div>
          </>
        )}
      </div>
    );
  }

  /* ---- Search field ---- */
  function SearchField({ value, onChange, placeholder }) {
    return (
      <div className="search">
        <Icon name="search" size={17} weight={2.2} style={{ color: "var(--label-2)" }} />
        <input value={value} placeholder={placeholder || "Search"}
          onChange={(e) => onChange(e.target.value)} />
        {value && (
          <button className="clear" onClick={() => onChange("")} aria-label="Clear">
            <Icon name="xmarkSmall" size={11} weight={2.6} />
          </button>
        )}
      </div>
    );
  }

  /* ---- iOS switch ---- */
  function Switch({ on, onChange }) {
    return (
      <button className={"switch " + (on ? "on" : "")} onClick={() => onChange(!on)} role="switch" aria-checked={on}>
        <span className="knob" />
      </button>
    );
  }

  /* ---- Chip ---- */
  function Chip({ label, icon, active, onClick, onRemove, editing }) {
    return (
      <button className={"chip " + (active ? "active" : "")} onClick={onClick}>
        {icon && !editing && <span className="chip-ico"><Icon name={icon} size={15} weight={2} /></span>}
        {label}
        {editing && onRemove && (
          <span className="x" onClick={(e) => { e.stopPropagation(); onRemove(); }}>
            <Icon name="xmarkSmall" size={9} weight={3} />
          </span>
        )}
      </button>
    );
  }

  /* ---- type badge label ---- */
  const TYPE_LABEL = { video: "Video", gif: "GIF", image: "Photo" };

  /* ---- Media tile + overlaid caption (editorial card) ---- */
  function Card({ item, index, liked, onOpen, onToggleLike, onHide, onMoreLikeThis, onLessLikeThis, onBlockTopic, onFollow, autoplay }) {
    const [previewing, setPreviewing] = useState(false);
    const [previewReady, setPreviewReady] = useState(false);
    const previewRef = useRef(null);
    const previewTimer = useRef(null);
    const canPreview = item.type !== "image" && item.mediaURL;

    useEffect(() => {
      setPreviewing(false);
      setPreviewReady(false);
      return () => clearTimeout(previewTimer.current);
    }, [item.id]);

    useEffect(() => {
      const video = previewRef.current;
      if (!video) return;
      if (!previewing) {
        video.pause();
        try { video.currentTime = 0; } catch (e) {}
        return;
      }
      video.muted = true;
      video.play().catch(() => {});
    }, [previewing, previewReady]);

    const startPreview = () => {
      if (!canPreview) return;
      if (window.matchMedia && !window.matchMedia("(hover: hover) and (pointer: fine)").matches) return;
      clearTimeout(previewTimer.current);
      previewTimer.current = setTimeout(() => {
        setPreviewReady(false);
        setPreviewing(true);
      }, 180);
    };

    const stopPreview = () => {
      clearTimeout(previewTimer.current);
      setPreviewing(false);
      setPreviewReady(false);
    };

    const onPreviewReady = () => {
      const video = previewRef.current;
      if (!video) return;
      setPreviewReady(true);
      video.muted = true;
      video.play().catch(() => {});
    };

    const onMove = (e) => {
      const r = e.currentTarget.getBoundingClientRect();
      e.currentTarget.style.setProperty("--mx", ((e.clientX - r.left) / r.width) * 100 + "%");
      e.currentTarget.style.setProperty("--my", ((e.clientY - r.top) / r.height) * 100 + "%");
    };
    const onKeyDown = (e) => {
      if (e.key === "Enter" || e.key === " ") {
        e.preventDefault();
        onOpen(item);
      }
    };
    return (
      <div className="card">
        <div className={"tile " + (previewReady ? "preview-on" : "")}
          role="button"
          tabIndex={0}
          aria-label={`Open ${item.title}`}
          style={{ paddingTop: item.ratio * 100 + "%" }}
          onClick={() => onOpen(item)}
          onKeyDown={onKeyDown}
          onMouseEnter={startPreview}
          onMouseLeave={stopPreview}
          onPointerEnter={startPreview}
          onPointerLeave={stopPreview}
          onPointerCancel={stopPreview}
          onBlur={stopPreview}
          onMouseMove={onMove}>
          <div className={"surface " + (autoplay && item.type !== "image" ? "shimmer" : "")}
            style={{ background: item.grad }}>
            {item.thumbnailURL && <img src={item.thumbnailURL} alt="" loading="lazy" decoding="async" />}
            {previewing && canPreview && (
              <video
                ref={previewRef}
                className={"preview-video " + (previewReady ? "is-ready" : "")}
                src={item.mediaURL}
                poster={item.thumbnailURL}
                muted
                playsInline
                loop
                preload="metadata"
                onLoadedData={onPreviewReady}
                onCanPlay={onPreviewReady}
                onError={stopPreview}
              />
            )}
          </div>
          <div className="sheen" />
          <button className={"like " + (liked ? "on" : "")}
            onClick={(e) => { e.stopPropagation(); onToggleLike(item.id); }} aria-label="Save">
            <Icon name={liked ? "heartFill" : "heart"} size={16} weight={2} />
          </button>
          {onHide && (
            <button className="hide-card"
              onClick={(e) => { e.stopPropagation(); onHide(item); }} aria-label="Hide post">
              <Icon name="trash" size={14} weight={2} />
            </button>
          )}
          <div className="feedback-card">
            {onMoreLikeThis && (
              <button onClick={(e) => { e.stopPropagation(); onMoreLikeThis(item); }} aria-label="More like this">
                <Icon name="sparkles" size={13} weight={2.2} />
              </button>
            )}
            {onLessLikeThis && (
              <button onClick={(e) => { e.stopPropagation(); onLessLikeThis(item); }} aria-label="Less like this">
                <Icon name="chevDown" size={13} weight={2.4} />
              </button>
            )}
            {onBlockTopic && (
              <button onClick={(e) => { e.stopPropagation(); onBlockTopic(item); }} aria-label="Block topic">
                <Icon name="xmarkSmall" size={13} weight={2.6} />
              </button>
            )}
          </div>
          {item.recommended && onFollow && (
            <button className="follow-topic"
              onClick={(e) => { e.stopPropagation(); onFollow(item); }}>
              Follow
            </button>
          )}
          {item.type === "video" && <span className="play"><Icon name="play" size={20} /></span>}
          <span className="badge">
            {item.type === "video" && <Icon name="play" size={9} />}
            {item.type === "video" ? item.dur : TYPE_LABEL[item.type]}
          </span>
          <div className="overlay">
            <div className="t">{item.title}</div>
            <div className="s">{item.source} · {item.interestLabel}</div>
          </div>
        </div>
      </div>
    );
  }

  /* ---- skeleton card ---- */
  function SkeletonCard({ ratio, index }) {
    return (
      <div className="card skel" style={{ animationDelay: index * 20 + "ms" }}>
        <div className="tile skel" style={{ paddingTop: ratio * 100 + "%" }}>
          <div className="surface shimmer" />
        </div>
        <div className="cap"><div className="t">.</div><div className="s">.</div></div>
      </div>
    );
  }

  Object.assign(window, { Segmented, SortMenu, SearchField, Switch, Chip, Card, SkeletonCard, TYPE_LABEL });
})();
