import { Link } from 'react-router-dom'
import { useOnboarding } from '../onboarding/OnboardingContext'
import { Badge, Card } from './ui'

const steps = [
  {
    id: 'account' as const,
    title: '建立經營帳號',
    desc: '從頂部帳號按鈕新增 Threads 經營帳號。',
    to: '/settings',
  },
  {
    id: 'connection' as const,
    title: '完成連線設定',
    desc: '在設定頁選擇正式模式（API）或開發模式，並完成對應連線。',
    to: '/settings',
  },
  {
    id: 'persona' as const,
    title: '建立人設',
    desc: '到人設庫建立至少一份語氣策略，發文時才能套用。',
    to: '/personas',
  },
]

function stepDone(id: (typeof steps)[number]['id'], status: ReturnType<typeof useOnboarding>) {
  if (id === 'account') return status.hasAccounts
  if (id === 'connection') return status.connectionReady
  return status.hasPersonas
}

export function OnboardingBanner() {
  const status = useOnboarding()

  if (status.loading || status.isComplete) return null

  const doneCount = steps.filter((step) => stepDone(step.id, status)).length

  return (
    <Card className="ac-onboarding-banner mb-4 border-brand/30 bg-brand-soft/35">
      <div className="flex flex-wrap items-start justify-between gap-3">
        <div className="min-w-0 flex-1">
          <p className="text-base font-bold text-ink">先完成入門設定，再開始巡樓</p>
          <p className="mt-1 text-sm leading-relaxed text-ink-secondary">
            經營帳號連線與人設都準備好後，總覽、任務、排程等功能才會出現在側欄。
          </p>
        </div>
        <Badge tone="brand">
          {doneCount}/{steps.length}
        </Badge>
      </div>

      <ol className="mt-4 grid gap-2 sm:grid-cols-3">
        {steps.map((step) => {
          const done = stepDone(step.id, status)
          const active = status.nextStep === step.id
          return (
            <li
              key={step.id}
              className={`ac-onboarding-step relative rounded-[var(--radius-md)] border px-3 py-3 ${
                active ? 'ac-onboarding-step--active hx-guide-glow' : ''
              }`}
            >
              <div className="flex flex-wrap items-center gap-2">
                <span
                  className={`ac-onboarding-step__dot ${done ? 'ac-onboarding-step__dot--done' : ''} ${
                    active ? 'ac-onboarding-step__dot--active' : ''
                  }`}
                  aria-hidden
                />
                <p className="min-w-0 flex-1 text-sm font-bold text-ink">{step.title}</p>
                {active ? (
                  <span className="ac-onboarding-step__badge" aria-hidden>
                    下一步
                  </span>
                ) : null}
              </div>
              <p className="mt-1.5 text-xs leading-relaxed text-ink-secondary">{step.desc}</p>
              {active ? (
                <Link to={step.to} className="mt-2 inline-block text-xs font-semibold text-brand hover:underline">
                  前往設定
                </Link>
              ) : null}
            </li>
          )
        })}
      </ol>
    </Card>
  )
}