"use client"
import { useEffect, useState } from 'react'
import Header from '@/components/Header'

export default function Dashboard(){
  const [me, setMe] = useState<any>(null)
  const [fbUrl, setFbUrl] = useState('')
  const [igUrl, setIgUrl] = useState('')
  const [replyText, setReplyText] = useState('문의 감사합니다! DM으로 상세 정보 보내드릴게요 😊')

  useEffect(()=>{
    fetch('/api/me').then(r=>r.json()).then(d=>{
      if(d.logged) setMe(d.user)
      else location.href='/'
    })
    const clientId = process.env.NEXT_PUBLIC_FB_APP_ID || '801356532268470'
    const fbRedirect = 'https://i.yjm.kr/api/auth/facebook/callback'
    const igRedirect = 'https://i.yjm.kr/api/auth/instagram/callback'
    const scopeFB = 'public_profile,email,pages_show_list,pages_read_engagement,pages_manage_posts,pages_manage_engagement'
    const scopeIG = 'instagram_basic,instagram_manage_comments,pages_show_list,pages_read_engagement'
    setFbUrl(`https://www.facebook.com/v20.0/dialog/oauth?client_id=${clientId}&redirect_uri=${encodeURIComponent(fbRedirect)}&scope=${encodeURIComponent(scopeFB)}&response_type=code`)
    setIgUrl(`https://www.facebook.com/v20.0/dialog/oauth?client_id=${clientId}&redirect_uri=${encodeURIComponent(igRedirect)}&scope=${encodeURIComponent(scopeIG)}&response_type=code`)
  },[])

  const saveReply = async () => {
    await fetch('/api/auto-reply', { method: 'POST', headers: {'Content-Type':'application/json'}, body: JSON.stringify({ reply_text: replyText }) })
    alert('자동댓글 저장 완료!')
  }

  if(!me) return <div className="p-10">로딩중...</div>

  return (
    <div className="min-h-screen bg-gray-50">
      <Header />
      <div className="max-w-3xl mx-auto p-6">
        <div className="bg-white rounded-2xl shadow p-8">
          <h1 className="text-2xl font-bold">안녕하세요, {me.name}님! <span className="text-sm font-normal text-gray-500">LV.{me.level}</span></h1>
          <p className="text-gray-500 mt-1">{me.email}</p>

          <div className="mt-8 grid gap-3">
            <h2 className="font-bold text-lg">1. SNS 연결 (개별 또는 한꺼번에)</h2>
            <div className="grid grid-cols-2 gap-3">
              <a href={fbUrl} className="block text-center bg-[#1877F2] text-white py-3 rounded-xl font-semibold">Facebook 페이지 연결</a>
              <a href={igUrl} className="block text-center bg-gradient-to-r from-pink-500 to-yellow-500 text-white py-3 rounded-xl font-semibold">Instagram 연결</a>
            </div>
            <div className="text-xs text-gray-400">FB 연결시 일반회원(LV2)으로 자동 승급, 무제한 이용</div>
          </div>

          <div className="mt-10 border-t pt-8">
            <h2 className="font-bold text-lg">2. 자동댓글 핵심 설정 (MVP)</h2>
            <p className="text-sm text-gray-500 mt-1">댓글이 달리면 아래 문구로 자동 답글을 답니다.</p>
            <textarea value={replyText} onChange={e=>setReplyText(e.target.value)} className="w-full mt-3 border rounded-xl p-3 h-24" />
            <button onClick={saveReply} className="mt-3 bg-black text-white px-5 py-2.5 rounded-xl">저장하고 활성화</button>
          </div>

          <div className="mt-10">
            <h3 className="font-bold">다음: /api/webhooks/facebook 웹훅 등록</h3>
            <p className="text-xs text-gray-500 mt-1">Meta 개발자 콘솔 {'>'} Webhooks {'>'} Subscribe: feed, comments {'>'} URL: https://i.yjm.kr/api/webhooks/facebook, Verify Token: {process.env.FB_VERIFY_TOKEN}</p>
          </div>
        </div>
      </div>
    </div>
  )
}
