import { useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useProfile } from '../../context/ProfileContext'
import { api } from '../../utils/api'

export default function GoalsFocusTeaserWidget({ refreshTick = 0 }) {
  const nav = useNavigate()
  const { activeProfile } = useProfile()
  const [goalsCount, setGoalsCount] = useState(null)

  useEffect(() => {
    if (!activeProfile?.id) return
    api
      .listGoals()
      .then((list) => setGoalsCount(Array.isArray(list) ? list.length : 0))
      .catch(() => setGoalsCount(null))
  }, [activeProfile?.id, refreshTick])

  return (
    <div className="card section-gap" style={{ marginBottom: 16 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
        <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--text1)' }}>Ziele &amp; Fokus</div>
        <button type="button" className="btn btn-secondary" style={{ fontSize: 12, padding: '6px 12px' }} onClick={() => nav('/goals')}>
          Bearbeiten →
        </button>
      </div>
      <div
        style={{ cursor: 'pointer' }}
        role="button"
        tabIndex={0}
        onKeyDown={(e) => e.key === 'Enter' && nav('/goals')}
        onClick={() => nav('/goals')}
      >
        {goalsCount != null && (
          <div style={{ fontSize: 13, fontWeight: 600, color: 'var(--text1)', marginBottom: 8 }}>
            {goalsCount === 0
              ? 'Noch keine Ziele angelegt.'
              : `${goalsCount} ${goalsCount === 1 ? 'Ziel' : 'Ziele'} im System.`}
          </div>
        )}
        <div style={{ fontSize: 12, color: 'var(--text2)' }}>
          Focus Areas und Fortschritt – tippen zum Öffnen der Ziele-Seite.
        </div>
      </div>
    </div>
  )
}
