// comments.jsx
const { useState, useEffect, useMemo } = React;

function formatTimeAgo(dateString) {
  const date = new Date(dateString);
  const now = new Date();
  const diffInSeconds = Math.floor((now - date) / 1000);

  if (diffInSeconds < 60) return "방금 전";
  if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)}분 전`;
  if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)}시간 전`;
  return `${Math.floor(diffInSeconds / 86400)}일 전`;
}

function CommentBadge({ side }) {
  if (!side) return null;
  const isYes = side === "yes";
  return (
    <span style={{
      display: "inline-block",
      padding: "2px 6px",
      borderRadius: 4,
      fontSize: 11,
      fontWeight: 700,
      background: isYes ? "rgba(0, 193, 118, 0.15)" : "rgba(229, 72, 77, 0.15)",
      color: isYes ? "#11B17C" : "#E5484D",
      marginLeft: 8,
      verticalAlign: "middle"
    }}>
      {isYes ? "예" : "아니오"}
    </span>
  );
}

function CommentItem({ comment, user, onDelete, C }) {
  return (
    <div style={{ display: "flex", gap: 12, padding: "16px 0", borderBottom: `1px solid ${C.hair}` }}>
      <img src={comment.user_picture || "Images/icons/default-avatar.png"} alt="Profile" style={{ width: 36, height: 36, borderRadius: "50%", objectFit: "cover", flexShrink: 0, border: `1px solid ${C.hair}` }} />
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 4 }}>
          <div style={{ display: "flex", alignItems: "center" }}>
            <span style={{ fontSize: 13.5, fontWeight: 700, color: C.ink }}>{comment.user_name}</span>
            <CommentBadge side={comment.vote_side} />
            <span style={{ fontSize: 12, color: C.ink3, marginLeft: 8 }}>{formatTimeAgo(comment.created_at)}</span>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
            {user && user.id === comment.user_id && (
              <button onClick={() => onDelete(comment.id)} style={{ border: "none", background: "none", cursor: "pointer", color: C.ink3, fontSize: 12, padding: 4 }}>삭제</button>
            )}
            <button style={{ border: "none", background: "none", cursor: "pointer", color: C.ink3, display: "flex", alignItems: "center", justifyContent: "center" }}>
              <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="1"/><circle cx="19" cy="12" r="1"/><circle cx="5" cy="12" r="1"/></svg>
            </button>
          </div>
        </div>
        <div style={{ fontSize: 14, color: C.ink, lineHeight: 1.5, wordBreak: "break-word", whiteSpace: "pre-wrap", marginBottom: 8 }}>
          {comment.content}
        </div>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <button style={{ border: "none", background: "none", cursor: "pointer", color: C.ink3, display: "flex", alignItems: "center", gap: 6, fontSize: 12, padding: 0 }}>
            <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 0 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z"/></svg>
            {comment.likes_count || 0}
          </button>
          <button style={{ border: "none", background: "none", cursor: "pointer", color: C.ink3, fontSize: 12, fontWeight: 600, padding: 0 }}>
            답글 달기
          </button>
        </div>
      </div>
    </div>
  );
}

window.CommentSection = function CommentSection({ ticker, user, C }) {
  const [comments, setComments] = useState([]);
  const [content, setContent] = useState("");
  const [isSubmitting, setIsSubmitting] = useState(false);
  
  // 현재 유저가 해당 종목(ticker)에 어떤 투표를 했는지 확인 (간단히 votes 테이블에서 가장 최근 투표 1개를 가져옴)
  // 완벽하게 하려면 여러 증권사 중 다수결이나 특정 로직이 필요하지만, 여기서는 단순화하여 하나라도 yes면 yes로 처리
  const [myVoteSide, setMyVoteSide] = useState(null);

  useEffect(() => {
    fetchComments();
    if (user) checkMyVote();
  }, [ticker, user]);

  async function checkMyVote() {
    const supabase = window.supabaseClient;
    if (!supabase || !user) return;
    try {
      const { data, error } = await supabase
        .from('votes')
        .select('vote')
        .eq('user_id', user.id)
        .eq('ticker', ticker)
        .limit(1);
      if (!error && data && data.length > 0) {
        setMyVoteSide(data[0].vote);
      } else {
        setMyVoteSide(null);
      }
    } catch (e) {}
  }

  async function fetchComments() {
    const supabase = window.supabaseClient;
    if (!supabase) return;
    try {
      const { data, error } = await supabase
        .from('comments')
        .select('*')
        .eq('ticker', ticker)
        .order('created_at', { ascending: false });
      
      if (!error && data) {
        setComments(data);
      }
    } catch (e) {
      console.error("Failed to fetch comments", e);
    }
  }

  async function handleSubmit() {
    if (!content.trim() || !user || isSubmitting) return;
    
    setIsSubmitting(true);
    const supabase = window.supabaseClient;
    try {
      const { data, error } = await supabase
        .from('comments')
        .insert({
          user_id: user.id,
          ticker: ticker,
          content: content.trim(),
          user_name: user.name,
          user_picture: user.picture,
          vote_side: myVoteSide
        })
        .select('*');
        
      if (error) {
        alert("댓글 작성 실패: " + (error.message || JSON.stringify(error)));
      } else if (data && data.length > 0) {
        setComments([data[0], ...comments]);
        setContent("");
      }
    } catch (e) {
      alert("댓글 작성 실패: " + e.message);
    } finally {
      setIsSubmitting(false);
    }
  }

  async function handleDelete(id) {
    if (!confirm("댓글을 삭제하시겠습니까?")) return;
    const supabase = window.supabaseClient;
    try {
      const { error } = await supabase.from('comments').delete().eq('id', id).eq('user_id', user.id);
      if (error) throw error;
      setComments(comments.filter(c => c.id !== id));
    } catch (e) {
      alert("삭제 실패: " + (e.message || JSON.stringify(e)));
    }
  }

  return (
    <div style={{ marginTop: 40, borderTop: `8px solid ${C.hair}`, paddingTop: 32 }}>
      {/* 헤더 부분 */}
      <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 20 }}>
        <h3 style={{ margin: 0, fontSize: 17, fontWeight: 800, color: C.ink }}>댓글 <span style={{ color: C.ink3 }}>({comments.length})</span></h3>
        <div style={{ display: "flex", gap: 16, fontSize: 13, fontWeight: 600, color: C.ink3 }}>
          <span style={{ cursor: "pointer", color: C.ink }}>상위 보유자</span>
          <span style={{ cursor: "pointer" }}>포지션</span>
          <span style={{ cursor: "pointer" }}>활동</span>
        </div>
      </div>

      {/* 입력 박스 */}
      <div style={{ 
        border: `1px solid ${C.hair2}`, borderRadius: 12, padding: "12px 16px",
        display: "flex", alignItems: "center", gap: 12, background: "#fff",
        boxShadow: "0 2px 8px rgba(0,0,0,0.02)", marginBottom: 24
      }}>
        <input 
          value={content}
          onChange={(e) => setContent(e.target.value)}
          placeholder={user ? "댓글 작성..." : "로그인 후 댓글을 작성할 수 있습니다."}
          disabled={!user || isSubmitting}
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSubmit(); } }}
          style={{ flex: 1, border: "none", outline: "none", fontSize: 14, background: "transparent", color: C.ink }}
        />
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <button style={{ border: "none", background: "none", cursor: "pointer", color: C.ink3, padding: 0, display: "flex" }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 14s1.5 2 4 2 4-2 4-2"/><line x1="9" y1="9" x2="9.01" y2="9"/><line x1="15" y1="9" x2="15.01" y2="9"/></svg>
          </button>
          <button style={{ border: "none", background: "none", cursor: "pointer", color: C.ink3, padding: 0, display: "flex" }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="8.5" cy="8.5" r="1.5"/><polyline points="21 15 16 10 5 21"/></svg>
          </button>
          <button 
            onClick={handleSubmit}
            disabled={!content.trim() || !user || isSubmitting}
            style={{ 
              background: content.trim() && user ? "#4F86F7" : "#E2E8F0", 
              color: content.trim() && user ? "#fff" : "#94A3B8",
              border: "none", borderRadius: 6, padding: "6px 14px", 
              fontSize: 13, fontWeight: 700, cursor: content.trim() && user ? "pointer" : "default",
              transition: "all .15s ease"
            }}>
            게시
          </button>
        </div>
      </div>

      {/* 필터 부분 */}
      <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", marginBottom: 20 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
          <span style={{ fontSize: 13, fontWeight: 600, color: C.ink, display: "flex", alignItems: "center", gap: 4, cursor: "pointer" }}>
            최신
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><polyline points="6 9 12 15 18 9"/></svg>
          </span>
          <label style={{ display: "flex", alignItems: "center", gap: 6, fontSize: 13, color: C.ink, fontWeight: 500, cursor: "pointer" }}>
            <input type="checkbox" style={{ accentColor: "#2D6FF2", width: 16, height: 16, borderRadius: 4 }} defaultChecked />
            보유자
          </label>
        </div>
        <div style={{ fontSize: 12, color: C.ink2, background: C.bg, padding: "4px 10px", borderRadius: 20, display: "flex", alignItems: "center", gap: 6, fontWeight: 500 }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>
          외부 링크에 주의하세요.
        </div>
      </div>

      {/* 댓글 리스트 */}
      <div style={{ minHeight: 200 }}>
        {comments.map(c => (
          <CommentItem key={c.id} comment={c} user={user} onDelete={handleDelete} C={C} />
        ))}
        {comments.length === 0 && (
          <div style={{ textAlign: "center", padding: "60px 0", color: C.ink3, fontSize: 14 }}>
            아직 작성된 댓글이 없습니다. 첫 번째 댓글을 남겨보세요!
          </div>
        )}
      </div>
    </div>
  );
};
