// tl-insta.jsx — Instagram feed via Behold public API
const { useEffect: useEffectIg, useState: useStateIg } = React;

const BEHOLD_FEED = "https://feeds.behold.so/pnruKWvZzbRvMWzMLAnf";

function InstaFeed() {
  const [posts, setPostsIg]   = useStateIg(null);   // null = loading, [] = failed
  const [profile, setProfile] = useStateIg(null);

  useEffectIg(() => {
    fetch(BEHOLD_FEED)
      .then(r => r.json())
      .then(data => {
        setProfile({
          username: data.username,
          bio: data.biography,
          avatar: data.profilePictureUrl,
          followers: data.followersCount,
        });
        setPostsIg((data.posts || []).slice(0, 6));
      })
      .catch(() => setPostsIg([]));
  }, []);

  const loading = posts === null;
  const failed  = Array.isArray(posts) && posts.length === 0;

  return (
    <section style={{ background: "var(--surface-2)", borderTop: "1px solid var(--hairline)" }}>
      <div className="tl-wrap" style={{ paddingTop: 72, paddingBottom: 72 }}>

        {/* Header */}
        <div className="tl-ig-head">
          <div style={{ display: "flex", alignItems: "center", gap: 20 }}>
            {profile && profile.avatar && (
              <img
                src={profile.avatar}
                alt={profile.username}
                style={{ width: 64, height: 64, borderRadius: "50%", objectFit: "cover", border: "2px solid var(--hairline)", flexShrink: 0 }}
              />
            )}
            <div>
              <Kicker>INSTAGRAM</Kicker>
              <h2 className="tl-h2" style={{ margin: "4px 0 0" }}>
                <a href={CONTACT.instagram} target="_blank" rel="noreferrer"
                   style={{ color: "var(--ink)", textDecoration: "none" }}>
                  {CONTACT.instaHandle}
                </a>
              </h2>
              {profile && (
                <p style={{ margin: "6px 0 0", fontSize: 14, color: "var(--muted)" }}>
                  팔로워 <strong style={{ color: "var(--ink)" }}>{profile.followers.toLocaleString()}</strong>명 · 틴트라이프의 현장과 시술 작업을 실시간으로 만나보세요.
                </p>
              )}
              {!profile && (
                <p className="tl-lead">틴트라이프의 현장과 시술 작업을 인스타그램에서 실시간으로 만나보세요.</p>
              )}
            </div>
          </div>
          <a href={CONTACT.instagram} target="_blank" rel="noreferrer" style={{ textDecoration: "none", flexShrink: 0 }}>
            <Button variant="soft">
              <span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
                <Icon name="instagram" size={18} />팔로우하기
              </span>
            </Button>
          </a>
        </div>

        {/* Grid */}
        {loading && (
          <div style={{ height: 280, display: "grid", placeItems: "center", color: "var(--muted)", fontSize: 14 }}>
            피드 불러오는 중…
          </div>
        )}

        {!loading && !failed && (
          <div className="tl-ig-grid" style={{ marginTop: 0 }}>
            {posts.map((post) => {
              const thumb = post.thumbnailUrl || post.mediaUrl;
              const isVideo = post.mediaType === "VIDEO";
              return (
                <a key={post.id} href={post.permalink} target="_blank" rel="noreferrer"
                   className="tl-ig-tile"
                   style={{ aspectRatio: "1 / 1", background: "var(--surface-2)" }}>
                  {thumb && (
                    <img
                      src={thumb}
                      alt={post.caption ? post.caption.slice(0, 60) : ""}
                      loading="lazy"
                      style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }}
                    />
                  )}
                  <span className="tl-ig-tile-ov">
                    <Icon name={isVideo ? "play" : "instagram"} size={26} />
                  </span>
                </a>
              );
            })}
          </div>
        )}

        {failed && (
          <div style={{ textAlign: "center", padding: "48px 0", color: "var(--muted)" }}>
            <a href={CONTACT.instagram} target="_blank" rel="noreferrer"
               style={{ color: "var(--accent)", fontWeight: 600, textDecoration: "none" }}>
              인스타그램에서 보기 →
            </a>
          </div>
        )}

        {/* Follow CTA card */}
        <a href={CONTACT.instagram} target="_blank" rel="noreferrer" className="tl-ig-card" style={{ marginTop: 24 }}>
          <span className="tl-ig-ic"><Icon name="instagram" size={20} /></span>
          <div>
            <div style={{ fontWeight: 700, color: "var(--ink)", fontSize: 15 }}>{CONTACT.instaHandle}</div>
            <div style={{ fontSize: 13, color: "var(--muted)", marginTop: 2 }}>팔로우하고 최신 소식 받기</div>
          </div>
        </a>

      </div>
    </section>
  );
}

Object.assign(window, { InstaFeed });
