// frontend/src/pages/crm/comms/helpdesk/HelpdeskPage.jsx
// Helpdesk hub — Issues tab + Support Tickets tab

import { useState } from 'react'
import PageHeader from '@/components/ui/PageHeader'
import Tabs from '@/components/ui/Tabs'
import Button from '@/components/ui/Button'
import { useAuth } from '@/hooks/useAuth'
import IssuesTab from './IssuesTab'
import TicketsTab from './TicketsTab'

const TABS = [
  { key: 'issues',  label: 'Issues'          },
  { key: 'tickets', label: 'Support Tickets'  },
]

export default function HelpdeskPage() {
  const { hasPermission } = useAuth()
  const canAdd = hasPermission('crm', 'add')

  const [activeTab, setActiveTab] = useState('issues')

  // Each counter increment signals the active tab to open its create modal
  const [issuesTrigger,  setIssuesTrigger]  = useState(0)
  const [ticketsTrigger, setTicketsTrigger] = useState(0)

  return (
    <div className="page-wrapper">
      <PageHeader title="Helpdesk">
        {canAdd && activeTab === 'issues' && (
          <Button variant="primary" size="md" onClick={() => setIssuesTrigger(n => n + 1)}>
            + New Issue
          </Button>
        )}
        {canAdd && activeTab === 'tickets' && (
          <Button variant="primary" size="md" onClick={() => setTicketsTrigger(n => n + 1)}>
            + Open New Ticket
          </Button>
        )}
      </PageHeader>

      <Tabs
        tabs={TABS}
        active={activeTab}
        onChange={setActiveTab}
        variant="line"
      />

      {activeTab === 'issues'  && <IssuesTab  onOpenCreate={issuesTrigger}  />}
      {activeTab === 'tickets' && <TicketsTab onOpenCreate={ticketsTrigger} />}
    </div>
  )
}
