// frontend/src/pages/crm/customers/tabs/OverviewTab.jsx
//
// Overview tab — hero stats bar + two-column layout.
// Left  (~40%, max 800px): Account Info · Contact Details · Staff Notes
// Right (flex 1): Latest Orders · Recent Communications
//
// --- DATA STRATEGY ---
// All hero stat values are derived from data the tab already fetches
// (orders, comms, quotations) to avoid extra Firestore reads.
// Fields that can't be derived cheaply (files_count, files_size_bytes,
// outstanding_balance, last_payment_date, open_issues_count,
// open_support_count, last_issue_date) should be denormalized onto the
// customer document by the backend whenever the respective sub-collection
// changes. This is the correct pattern — one read, no fan-out.

import { useState, useEffect, useRef } from 'react'
import { useNavigate } from 'react-router-dom'
import api from '@/lib/api'
import Card from '@/components/ui/Card'
import Icon from '@/components/ui/Icon'
import Button from '@/components/ui/Button'
import StatusBadge from '@/components/ui/StatusBadge'
import Spinner from '@/components/ui/Spinner'
import NoteModal from '@/modals/crm/customers/NoteModal'

// ─── Constants ────────────────────────────────────────────────────────────────

const LANGUAGE_LABELS = {
  af:'Afrikaans',sq:'Albanian',am:'Amharic',ar:'Arabic',hy:'Armenian',
  az:'Azerbaijani',eu:'Basque',be:'Belarusian',bn:'Bengali',bs:'Bosnian',
  bg:'Bulgarian',ca:'Catalan',zh:'Chinese',hr:'Croatian',cs:'Czech',
  da:'Danish',nl:'Dutch',en:'English',et:'Estonian',fi:'Finnish',
  fr:'French',ka:'Georgian',de:'German',el:'Greek',gu:'Gujarati',
  he:'Hebrew',hi:'Hindi',hu:'Hungarian',id:'Indonesian',it:'Italian',
  ja:'Japanese',kn:'Kannada',kk:'Kazakh',ko:'Korean',lv:'Latvian',
  lt:'Lithuanian',mk:'Macedonian',ms:'Malay',ml:'Malayalam',mt:'Maltese',
  mr:'Marathi',mn:'Mongolian',ne:'Nepali',no:'Norwegian',fa:'Persian',
  pl:'Polish',pt:'Portuguese',pa:'Punjabi',ro:'Romanian',ru:'Russian',
  sr:'Serbian',si:'Sinhala',sk:'Slovak',sl:'Slovenian',es:'Spanish',
  sw:'Swahili',sv:'Swedish',tl:'Tagalog',ta:'Tamil',te:'Telugu',
  th:'Thai',tr:'Turkish',uk:'Ukrainian',ur:'Urdu',uz:'Uzbek',
  vi:'Vietnamese',cy:'Welsh',yi:'Yiddish',zu:'Zulu',
}

const REL_STATUS_META = {
  lead:     { label: 'Lead',     variant: 'info',    description: 'Potential new lead — no active engagement yet.' },
  prospect: { label: 'Prospect', variant: 'warning', description: 'Actively engaged — exploring possibilities.' },
  active:   { label: 'Active',   variant: 'success', description: 'Active customer with ongoing commercial activity.' },
  inactive: { label: 'Archived',  variant: 'neutral', description: 'Customer has completed all engagements.' },
  churned:  { label: 'Went Cold', variant: 'danger',  description: 'Customer disengaged. Might need a follow up' },
}

const ACCENT_COLOR = {
  success: 'var(--color-success)',
  warning: 'var(--color-warning)',
  danger:  'var(--color-danger)',
  info:    'var(--color-info)',
  neutral: 'var(--color-text-muted)',
}
const ACCENT_BG = {
  success: 'var(--color-success-bg)',
  warning: 'var(--color-warning-bg)',
  danger:  'var(--color-danger-bg)',
  info:    'var(--color-info-bg)',
  neutral: 'var(--color-bg-elevated)',
}

const TYPE_META = {
  email:     { label: 'Email',     icon: '/src/assets/comms/email.svg',    color: 'var(--color-info)',       bg: 'var(--color-info-bg)' },
  whatsapp:  { label: 'WhatsApp',  icon: '/src/assets/comms/whatsapp.svg', color: 'var(--color-success)',    bg: 'var(--color-success-bg)' },
  call:      { label: 'Call',      icon: '/src/assets/comms/call.svg',     color: 'var(--color-warning)',    bg: 'var(--color-warning-bg)' },
  sms:       { label: 'SMS',       icon: '/src/assets/comms/sms.svg',      color: 'var(--color-warning)',    bg: 'var(--color-warning-bg)' },
  note:      { label: 'Note',      icon: '/src/assets/comms/note.svg',     color: 'var(--color-text-muted)', bg: 'var(--color-bg-elevated)' },
  in_person: { label: 'In person', icon: '/src/assets/comms/inperson.svg', color: 'var(--color-primary)',    bg: 'var(--color-primary-subtle)' },
}

const ORDER_STATUS_META = {
  draft:            { label: 'Draft',            variant: 'neutral' },
  confirmed:        { label: 'Confirmed',        variant: 'info'    },
  in_production:    { label: 'In Production',    variant: 'warning' },
  ready_to_ship:    { label: 'Ready to Ship',    variant: 'info'    },
  shipped:          { label: 'Shipped',          variant: 'info'    },
  delivered:        { label: 'Delivered',        variant: 'success' },
  cancelled:        { label: 'Cancelled',        variant: 'danger'  },
  awaiting_payment: { label: 'Awaiting Payment', variant: 'warning' },
  paid:             { label: 'Paid',             variant: 'success' },
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

function formatRelative(val) {
  if (!val) return ''
  const diff = Date.now() - new Date(val).getTime()
  if (diff < 0)  return 'just now'
  const s = Math.floor(diff / 1000)
  if (s < 60)   return 'just now'
  const m = Math.floor(s / 60)
  if (m < 60)   return `${m}m ago`
  const h = Math.floor(m / 60)
  if (h < 24)   return `${h}h ago`
  const d = Math.floor(h / 24)
  if (d === 1)  return 'yesterday'
  if (d < 7)    return `${d} days ago`
  const w = Math.floor(d / 7)
  if (w < 5)    return `${w} week${w !== 1 ? 's' : ''} ago`
  const mo = Math.floor(d / 30)
  if (mo < 12)  return `${mo} month${mo !== 1 ? 's' : ''} ago`
  return `${Math.floor(d / 365)} year${Math.floor(d / 365) !== 1 ? 's' : ''} ago`
}


function formatCurrency(val, currency = 'EUR') {
  if (val == null) return null
  return new Intl.NumberFormat('en-DE', { style: 'currency', currency, minimumFractionDigits: 2 }).format(val)
}


function buildAddress(loc) {
  if (!loc) return null
  return [loc.address, loc.city, loc.postal_code, loc.region, loc.country].filter(Boolean).join(', ')
}

// ─── Helpers ──────────────────────────────────────────────────────────────────

// Zero-pad single digit numbers: 5 → "05", 12 → "12", 0 → "00"
function padNum(n) {
  if (n == null) return '00'
  const num = typeof n === 'number' ? n : parseFloat(n)
  if (Number.isNaN(num)) return String(n) // non-numeric (currency strings etc) — pass through
  return num < 10 && num >= 0 ? `0${Math.floor(num)}` : String(Math.floor(num))
}

// ─── Stat cell — label / (value + subtitle inline) ────────────────────────────
// Each cell is centered in its grid column. All cells in a row share the same
// column width via CSS grid on the parent (see HeroStatsBar).

function StatCell({ label, value, sub, accentColor, loading }) {
  const isResolved = !loading && value != null
  const displayed  = isResolved ? (typeof value === 'number' ? padNum(value) : String(value)) : '00'

  return (
    <div style={{
      display: 'flex',
      flexDirection: 'column',
      justifyContent: 'center',
      alignItems: 'flex-start',
      gap: 'var(--space-1)',
      padding: 'var(--space-4) 0',
    }}>
      {/* Label */}
      <span className="card-field-label" style={{ whiteSpace: 'nowrap' }}>
        {label}
      </span>

      {/* Value + subtitle inline */}
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 'var(--space-2)' }}>
        <span style={{
          fontSize: '1.35rem',
          fontWeight: 800,
          fontFamily: 'var(--font-family-display)',
          letterSpacing: 'var(--tracking-tight)',
          color: isResolved ? (accentColor || 'var(--color-text-primary)') : 'var(--color-text-muted)',
          transition: 'color 0.3s',
          lineHeight: 1.1,
          whiteSpace: 'nowrap',
        }}>
          {displayed}
        </span>
        {sub && (
          <span style={{
            fontSize: 'var(--font-size-xs)',
            color: 'var(--color-text-secondary)',
            whiteSpace: 'nowrap',
            overflow: 'hidden',
            textOverflow: 'ellipsis',
            lineHeight: 1,
          }}>
            {loading ? '—' : sub}
          </span>
        )}
      </div>
    </div>
  )
}

// ─── Status panel — left 20%, full height of the hero ─────────────────────────

function StatusPanel({ customer, canEdit, onUpdated }) {
  const status = customer.relationship_status || 'lead'
  const meta   = REL_STATUS_META[status] || REL_STATUS_META.lead
  const accent = ACCENT_COLOR[meta.variant]
  const bg     = ACCENT_BG[meta.variant]

  const [open, setOpen]     = useState(false)
  const [saving, setSaving] = useState(false)
  const ref = useRef(null)

  useEffect(() => {
    if (!open) return
    const handler = e => { if (ref.current && !ref.current.contains(e.target)) setOpen(false) }
    document.addEventListener('mousedown', handler)
    return () => document.removeEventListener('mousedown', handler)
  }, [open])

  const handleSelect = async newStatus => {
    if (!canEdit || newStatus === status) { setOpen(false); return }
    setSaving(true); setOpen(false)
    try {
      const updated = await api.patch(`/crm/customers/${customer.id}/relationship-status`, { status: newStatus })
      onUpdated(updated)
    } catch (err) {
      console.error('Status update failed:', err.message)
    } finally {
      setSaving(false)
    }
  }

  return (
    <div ref={ref} style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'flex-start',
      justifyContent: 'center',
      padding: 'var(--space-6) var(--space-6)',
      gap: 'var(--space-3)',
      position: 'relative',
      backgroundColor: bg,
      borderRadius: 'var(--radius-xl) 0 0 var(--radius-xl)',
      // Subtle tinted left border accent
      borderRight: '1px solid var(--color-border)',
      minHeight: '100%',
      transition: 'background-color 0.3s',
    }}>

      {/* Label */}
      <span className="card-field-label" style={{ color: accent, opacity: 0.8 }}>
        Relationship
      </span>

      {/* Big pulsing dot + status name */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
        <span style={{
          width: 10, height: 10,
          borderRadius: '50%',
          backgroundColor: accent,
          flexShrink: 0,
          animation: meta.variant === 'success' ? 'overview-pulse 2s ease-in-out infinite' : 'none',
        }} />
        <span style={{
          fontSize: '1.2rem',
          fontWeight: 800,
          fontFamily: 'var(--font-family-display)',
          color: accent,
          letterSpacing: 'var(--tracking-tight)',
          lineHeight: 1,
        }}>
          {meta.label}
        </span>
      </div>

      {/* Description */}
      <p style={{
        fontSize: 'var(--font-size-sm)',
        color: accent,
        opacity: 0.75,
        lineHeight: 1.4,
        margin: 0,
      }}>
        {meta.description}
      </p>

      {/* Change button */}
      {canEdit && (
        <button
          type="button"
          disabled={saving}
          onClick={() => setOpen(v => !v)}
          style={{
            marginTop: 'var(--space-1)',
            display: 'inline-flex',
            alignItems: 'center',
            gap: 'var(--space-1)',
            padding: '4px 10px',
            borderRadius: 'var(--radius-full)',
            backgroundColor: 'transparent',
            border: `1px solid ${accent}`,
            color: accent,
            cursor: 'pointer',
            fontSize: 'var(--font-size-xs)',
            fontWeight: 'var(--font-weight-semibold)',
            fontFamily: 'var(--font-family-base)',
            opacity: saving ? 0.5 : 0.8,
            transition: 'opacity var(--transition-fast)',
          }}
          onMouseEnter={e => { e.currentTarget.style.opacity = '1' }}
          onMouseLeave={e => { e.currentTarget.style.opacity = saving ? '0.5' : '0.8' }}
        >
          Change
          <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <polyline points="6 9 12 15 18 9" />
          </svg>
        </button>
      )}

      {/* Dropdown — opens downward */}
      {open && (
        <div style={{
          position: 'absolute',
          top: 'calc(100% + var(--space-2))',
          left: 0,
          right: 0,
          zIndex: 50,
          backgroundColor: 'var(--color-bg-elevated)',
          border: '1px solid var(--color-border-strong)',
          borderRadius: 'var(--radius-lg)',
          boxShadow: 'var(--shadow-lg)',
          overflow: 'hidden',
        }}>
          {Object.entries(REL_STATUS_META).map(([key, m], i) => (
            <button
              key={key}
              type="button"
              onClick={() => handleSelect(key)}
              style={{
                display: 'flex', alignItems: 'flex-start', gap: 'var(--space-3)',
                width: '100%',
                padding: 'var(--space-3) var(--space-4)',
                borderTop: i > 0 ? '1px solid var(--color-border)' : 'none',
                backgroundColor: key === status ? ACCENT_BG[m.variant] : 'transparent',
                border: 'none', cursor: 'pointer', textAlign: 'left',
                transition: 'background-color var(--transition-fast)',
              }}
              onMouseEnter={e => { if (key !== status) e.currentTarget.style.backgroundColor = 'var(--color-bg-island)' }}
              onMouseLeave={e => { if (key !== status) e.currentTarget.style.backgroundColor = key === status ? ACCENT_BG[m.variant] : 'transparent' }}
            >
              <span style={{
                marginTop: 3,
                width: 8, height: 8, borderRadius: '50%',
                backgroundColor: ACCENT_COLOR[m.variant],
                flexShrink: 0,
              }} />
              <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                <span style={{
                  fontSize: 'var(--font-size-base)',
                  fontWeight: 'var(--font-weight-semibold)',
                  color: key === status ? ACCENT_COLOR[m.variant] : 'var(--color-text-primary)',
                }}>
                  {m.label}
                </span>
                <span style={{
                  fontSize: 'var(--font-size-sm)',
                  color: 'var(--color-text-muted)',
                  lineHeight: 1.4,
                }}>
                  {m.description}
                </span>
              </div>
            </button>
          ))}
        </div>
      )}
    </div>
  )
}

// ─── Hero section — 20/80 split ───────────────────────────────────────────────
//
// Left  20%: StatusPanel — tinted bg, big status name, description, change button
// Right 80%: 4-column × 2-row stats grid
//   Row 1: Orders | Balance | Issues | Support
//   Row 2: Communications | Quotations | Files | Devices

function HeroStatsBar({ customer, orders, comms, quotations, ordersLoading, commsLoading, quotesLoading, onStatusUpdated }) {

  // ── Communications ─────────────────────────────────────────────────────────
  const commsCount   = comms.length
  const lastComm     = comms[0]
  const lastCommDate = lastComm ? formatRelative(lastComm.occurred_at || lastComm.created_at) : null

  // ── Quotations ─────────────────────────────────────────────────────────────
  const quotesCount   = quotations.length
  const lastQuote     = quotations[0]
  const lastQuoteDate = lastQuote ? formatRelative(lastQuote.created_at || lastQuote.date) : null

  // ── Orders ─────────────────────────────────────────────────────────────────
  const openOrders        = orders.filter(o => !['delivered', 'cancelled', 'paid'].includes(o.status))
  const latestOrder       = orders[0]
  const latestOrderStatus = latestOrder ? (ORDER_STATUS_META[latestOrder.status]?.label || latestOrder.status) : null

  // ── Balance ────────────────────────────────────────────────────────────────
  const txHistory = customer.transaction_history || []
  const totalInvoiced = txHistory.filter(tx => tx.flow === 'invoice').reduce((s, tx) => s + (tx.amount || 0), 0)
  const totalPaid     = txHistory.filter(tx => tx.flow === 'payment').reduce((s, tx) => s + (tx.amount || 0), 0)
  const outstanding   = txHistory.length ? (totalInvoiced - totalPaid) : null
  const lastPayTx     = [...txHistory].reverse().find(tx => tx.flow === 'payment')
  const lastPayDate   = lastPayTx?.date ? formatRelative(lastPayTx.date) : null
  const balanceDisplay = outstanding == null ? null
    : Math.abs(outstanding) < 0.01 ? '€0'
    : formatCurrency(Math.abs(outstanding))
  const balanceSub   = outstanding == null             ? null
    : Math.abs(outstanding) < 0.01                    ? 'all settled'
    : outstanding > 0                                 ? (lastPayDate || 'outstanding')
    :                                                   'credit'
  const balanceColor = outstanding == null             ? undefined
    : Math.abs(outstanding) < 0.01                    ? 'var(--color-success)'
    : outstanding > 0                                 ? 'var(--color-warning)'
    :                                                   'var(--color-info)'

  // ── Files ──────────────────────────────────────────────────────────────────
  const filesCount = null // no backend field yet

  // ── Devices ────────────────────────────────────────────────────────────────
  const totalDevices = (customer.owned_items || []).length

  // ── Issues & Support ───────────────────────────────────────────────────────
  const summary        = customer.crm_summary || {}
  const openIssues     = summary.active_issues_count  ?? (customer.technical_issues || []).filter(i => i.active).length
  const openSupport    = summary.active_support_count ?? (customer.install_support   || []).filter(i => i.active).length
  const lastIssueDateRel   = summary.latest_issue_date   ? formatRelative(summary.latest_issue_date)   : null
  const lastSupportDateRel = summary.latest_support_date ? formatRelative(summary.latest_support_date) : null

  return (
    <div style={{
      display: 'flex',
      alignItems: 'stretch',
      backgroundColor: 'var(--color-bg-surface)',
      border: '1px solid var(--color-border)',
      borderRadius: 'var(--radius-xl)',
      boxShadow: 'var(--shadow-card)',
      overflow: 'visible',
    }}>

      {/* ── Left 20%: Status panel ── */}
      <div style={{ flex: '0 0 20%', minWidth: 0 }}>
        <StatusPanel customer={customer} canEdit onUpdated={onStatusUpdated} />
      </div>

      {/* ── Right 80%: 4×2 grid, columns fixed-width, centered in the space ── */}
      <div style={{
        flex: 1,
        minWidth: 0,
        display: 'grid',
        gridTemplateColumns: 'repeat(4, minmax(120px, 180px))',
        gridTemplateRows: 'repeat(2, auto)',
        alignContent: 'center',
        alignItems: 'center',
        justifyContent: 'space-evenly',
        gap: 'var(--space-0)',
        paddingLeft: 'var(--space-6)',
      }}>
        {/* Row 1: Orders | Balance | Issues | Support */}
        <StatCell
          label="Orders"
          value={ordersLoading ? null : openOrders.length}
          sub={ordersLoading ? null : (latestOrderStatus || 'all closed')}
          accentColor={!ordersLoading && openOrders.length ? 'var(--color-info)' : undefined}
          loading={ordersLoading}
        />
        <StatCell
          label="Balance"
          value={balanceDisplay}
          sub={balanceSub}
          accentColor={balanceColor}
          loading={false}
        />
        <StatCell
          label="Issues"
          value={openIssues}
          sub={lastIssueDateRel || (openIssues === 0 ? 'none active' : null)}
          accentColor={openIssues > 0 ? 'var(--color-danger)' : undefined}
          loading={false}
        />
        <StatCell
          label="Support"
          value={openSupport}
          sub={lastSupportDateRel || (openSupport === 0 ? 'none active' : null)}
          accentColor={openSupport > 0 ? 'var(--color-warning)' : undefined}
          loading={false}
        />
        {/* Row 2: Communications | Quotations | Files | Devices */}
        <StatCell
          label="Communications"
          value={commsLoading ? null : commsCount}
          sub={commsLoading ? null : (lastCommDate || 'none yet')}
          loading={commsLoading}
        />
        <StatCell
          label="Quotations"
          value={quotesLoading ? null : quotesCount}
          sub={quotesLoading ? null : (lastQuoteDate || 'none yet')}
          loading={quotesLoading}
        />
        <StatCell
          label="Files"
          value={filesCount}
          sub="coming soon"
          loading={false}
        />
        <StatCell
          label="Devices"
          value={totalDevices}
          sub={totalDevices ? 'owned' : 'none linked'}
          loading={false}
        />
      </div>

    </div>
  )
}

// ─── Vertical info field: label above value (matches card-body spacing) ────────

function InfoField({ label, children }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-1)' }}>
      <span className="card-field-label">{label}</span>
      <div style={{
        fontSize: 'var(--font-size-base)',
        color: 'var(--color-text-primary)',
        lineHeight: 1.5,
      }}>
        {children || <span style={{ color: 'var(--color-text-muted)' }}>—</span>}
      </div>
    </div>
  )
}

// ─── Contact row ──────────────────────────────────────────────────────────────

const CONTACT_ICONS = {
  email: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <rect x="2" y="4" width="20" height="16" rx="2"/><polyline points="2,4 12,13 22,4"/>
    </svg>
  ),
  phone: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07A19.5 19.5 0 014.5 12 19.79 19.79 0 011.35 3.5 2 2 0 013.32 1.35h3a2 2 0 012 1.72c.127.96.361 1.903.7 2.81a2 2 0 01-.45 2.11L7.91 8.96a16 16 0 006.29 6.29l1.28-1.28a2 2 0 012.11-.45c.907.339 1.85.573 2.81.7A2 2 0 0122 16.92z"/>
    </svg>
  ),
  whatsapp: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor">
      <path d="M12 2C6.477 2 2 6.477 2 12c0 1.89.518 3.66 1.421 5.182L2 22l4.985-1.387A9.945 9.945 0 0012 22c5.523 0 10-4.477 10-10S17.523 2 12 2zm4.93 14.07c-.207.583-1.218 1.11-1.667 1.148-.45.04-.87.2-2.933-.61-2.47-.98-4.02-3.47-4.14-3.63-.12-.16-.98-1.3-.98-2.48 0-1.18.62-1.76.84-2 .22-.24.48-.3.64-.3.16 0 .32 0 .46.007.15.007.35-.057.548.418.207.494.7 1.7.76 1.824.06.12.1.264.02.43-.08.163-.12.264-.24.406-.12.142-.253.317-.36.426-.12.12-.245.25-.105.49.14.24.622.997 1.338 1.615.918.815 1.69 1.067 1.93 1.187.24.12.38.1.52-.06.14-.16.6-.7.76-.94.16-.24.32-.2.54-.12.22.08 1.4.66 1.64.78.24.12.4.18.46.28.06.1.06.583-.147 1.166z"/>
    </svg>
  ),
  other: (
    <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      <path d="M10 13a5 5 0 007.54.54l3-3a5 5 0 00-7.07-7.07l-1.72 1.71"/>
      <path d="M14 11a5 5 0 00-7.54-.54l-3 3a5 5 0 007.07 7.07l1.71-1.71"/>
    </svg>
  ),
}

const CONTACT_COLOR = {
  email:    { color: 'var(--color-info)',    bg: 'var(--color-info-bg)' },
  phone:    { color: 'var(--color-success)', bg: 'var(--color-success-bg)' },
  whatsapp: { color: 'var(--color-success)', bg: 'var(--color-success-bg)' },
  other:    { color: 'var(--color-text-muted)', bg: 'var(--color-bg-elevated)' },
}

function ContactRow({ type, value, label, primary }) {
  const icon  = CONTACT_ICONS[type]  || CONTACT_ICONS.other
  const style = CONTACT_COLOR[type]  || CONTACT_COLOR.other
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
      <div style={{
        width: 36, height: 36,
        borderRadius: 'var(--radius-lg)',
        backgroundColor: style.bg,
        color: style.color,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        {icon}
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 2, minWidth: 0, flex: 1 }}>
        <span style={{
          fontSize: 'var(--font-size-base)',
          color: 'var(--color-text-primary)',
          fontWeight: 'var(--font-weight-medium)',
          overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
        }}>
          {value}
        </span>
        <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
          {primary && (
            <span style={{
              fontSize: '10px',
              fontWeight: 'var(--font-weight-bold)',
              color: 'var(--color-primary)',
              backgroundColor: 'var(--color-primary-subtle)',
              padding: '1px 5px',
              borderRadius: 'var(--radius-full)',
              letterSpacing: 'var(--tracking-wide)',
              textTransform: 'uppercase',
              lineHeight: 1.6,
            }}>
              Primary
            </span>
          )}
          {label && (
            <span className="card-field-label">{label}</span>
          )}
        </div>
      </div>
    </div>
  )
}

// ─── Staff note row ────────────────────────────────────────────────────────────

function NoteRow({ note, index, canEdit, onEdit }) {
  const [hovered, setHovered] = useState(false)
  const text = note.text || note.content || note.body || ''
  const author = note.by || note.author_name || note.staff_name || 'Staff'
  const date = note.at || note.updated_at || note.created_at

  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      style={{
        padding: 'var(--space-3) var(--space-4)',
        borderRadius: 'var(--radius-md)',
        backgroundColor: 'var(--color-bg-abyss)',
        border: '1px solid var(--color-border)',
        position: 'relative',
        transition: 'border-color var(--transition-fast)',
        borderColor: hovered ? 'var(--color-border-strong)' : 'var(--color-border)',
      }}
    >
      {/* Note text — preserves newlines */}
      <p style={{
        fontSize: 'var(--font-size-base)',
        color: 'var(--color-text-primary)',
        lineHeight: 1.6,
        margin: '0 0 var(--space-2)',
        whiteSpace: 'pre-wrap',
        wordBreak: 'break-word',
        paddingRight: canEdit && hovered ? 'var(--space-16)' : 0,
        transition: 'padding-right var(--transition-fast)',
      }}>
        {text || <span style={{ color: 'var(--color-text-muted)', fontStyle: 'italic' }}>Empty note</span>}
      </p>

      {/* Footer: author · date */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)' }}>
        <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-medium)' }}>
          {author}
        </span>
        {date && (
          <>
            <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-border-strong)' }}>·</span>
            <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
              {formatRelative(date)}
            </span>
          </>
        )}
      </div>

      {/* Hover edit button */}
      {canEdit && hovered && (
        <div style={{ position: 'absolute', top: 'var(--space-3)', right: 'var(--space-3)' }}>
          <Button variant="table-actions" size="sm" onClick={() => onEdit(index, note)}>Edit</Button>
        </div>
      )}
    </div>
  )
}

function StaffNotes({ notes, canEdit, onEdit }) {
  if (!notes?.length) {
    return <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', margin: 0 }}>No notes yet.</p>
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-3)' }}>
      {notes.map((note, i) => (
        <NoteRow key={note.id || i} note={note} index={i} canEdit={canEdit} onEdit={onEdit} />
      ))}
    </div>
  )
}

// ─── Comm timeline entry ──────────────────────────────────────────────────────

function CommEntry({ comm, isLast, onNavigateToComms }) {
  const [hovered, setHovered] = useState(false)
  const meta = TYPE_META[comm.type] || TYPE_META.note
  return (
    <div
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
      onClick={onNavigateToComms}
      style={{
        display: 'flex', gap: 'var(--space-4)',
        paddingBottom: isLast ? 0 : 'var(--space-5)',
        position: 'relative',
        cursor: 'pointer',
        borderRadius: 'var(--radius-md)',
        margin: '0 calc(-1 * var(--space-4))',
        padding: `var(--space-3) var(--space-4) ${isLast ? 'var(--space-3)' : 'var(--space-5)'}`,
        backgroundColor: hovered ? 'var(--color-bg-elevated)' : 'transparent',
        transition: 'background-color var(--transition-fast)',
      }}>
      {!isLast && (
        <div style={{
          position: 'absolute', left: 19, top: 40, bottom: 0,
          width: 1, backgroundColor: 'var(--color-border)',
        }} />
      )}
      <div style={{
        width: 40, height: 40, borderRadius: 'var(--radius-full)',
        backgroundColor: meta.bg,
        border: '3px solid var(--color-bg-surface)',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0, zIndex: 1,
      }}>
        <img src={meta.icon} alt={meta.label} style={{ width: 18, height: 18, opacity: 0.85 }} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 'var(--space-2)', marginBottom: 4 }}>
          <span style={{
            fontSize: 'var(--font-size-base)',
            fontWeight: 'var(--font-weight-semibold)',
            color: 'var(--color-text-primary)',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', flex: 1,
          }}>
            {comm.subject || `${meta.label} ${comm.direction === 'inbound' ? 'received' : 'sent'}`}
          </span>
          <span style={{
            fontSize: 'var(--font-size-xs)',
            color: 'var(--color-text-muted)',
            whiteSpace: 'nowrap',
            textTransform: 'uppercase',
            letterSpacing: 'var(--tracking-wide)',
            fontWeight: 'var(--font-weight-semibold)',
          }}>
            {formatRelative(comm.occurred_at || comm.created_at)}
          </span>
        </div>
        {(comm.from_name || comm.staff_name) && (
          <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-2)', marginBottom: 4 }}>
            <div style={{
              width: 18, height: 18, borderRadius: 'var(--radius-full)',
              backgroundColor: 'var(--color-bg-island)',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: '10px', fontWeight: 'var(--font-weight-bold)',
              color: 'var(--color-text-secondary)', flexShrink: 0,
            }}>
              {(comm.from_name || comm.staff_name || '?').charAt(0).toUpperCase()}
            </div>
            <span style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)' }}>
              {comm.from_name || comm.staff_name}
            </span>
          </div>
        )}
        {comm.body && (
          <p style={{
            fontSize: 'var(--font-size-sm)',
            color: 'var(--color-text-secondary)',
            lineHeight: 1.5,
            display: '-webkit-box',
            WebkitLineClamp: 2,
            WebkitBoxOrient: 'vertical',
            overflow: 'hidden',
            margin: 0,
          }}>
            {comm.body}
          </p>
        )}
      </div>
    </div>
  )
}

// ─── Main component ───────────────────────────────────────────────────────────

export default function OverviewTab({ customer, canEdit, onCustomerUpdated, onTabChange }) {
  const navigate   = useNavigate()
  const customerId = customer.id

  const [orders,        setOrders]        = useState([])
  const [comms,         setComms]         = useState([])
  const [quotations,    setQuotations]    = useState([])
  const [ordersLoading, setOrdersLoading] = useState(true)
  const [commsLoading,  setCommsLoading]  = useState(true)
  const [quotesLoading, setQuotesLoading] = useState(true)

  // Note modal: null | { editIndex: number|null, initialData: object|null }
  const [noteModal, setNoteModal] = useState(null)

  useEffect(() => {
    setOrdersLoading(true)
    api.get(`/crm/customers/${customerId}/orders`)
      .then(d => setOrders(d.orders || []))
      .catch(() => setOrders([]))
      .finally(() => setOrdersLoading(false))
  }, [customerId])

  useEffect(() => {
    setCommsLoading(true)
    api.get(`/crm/comms?customer_id=${customerId}&limit=5`)
      .then(d => setComms(d.entries || []))
      .catch(() => setComms([]))
      .finally(() => setCommsLoading(false))
  }, [customerId])

  useEffect(() => {
    setQuotesLoading(true)
    api.get(`/crm/quotations/customer/${customerId}`)
      .then(d => setQuotations((d.quotations || []).slice(0, 5)))
      .catch(() => setQuotations([]))
      .finally(() => setQuotesLoading(false))
  }, [customerId])

  // Derived values
  const contacts    = customer.contacts || []
  const billingAddr = buildAddress(customer.billing_location || customer.location)
  const langLabel   = LANGUAGE_LABELS[customer.language] || customer.language || null
  const tags        = customer.tags || []
  const notes       = customer.notes || []
  const latestOrders  = orders.slice(0, 5)
  const recentComms   = comms.slice(0, 5)

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>

      {/* ── Hero Stats Bar ─────────────────────────────────────────────── */}
      <HeroStatsBar
        customer={customer}
        orders={orders}
        comms={comms}
        quotations={quotations}
        ordersLoading={ordersLoading}
        commsLoading={commsLoading}
        quotesLoading={quotesLoading}
        onStatusUpdated={onCustomerUpdated}
      />

      {/* ── Two-column layout ──────────────────────────────────────────── */}
      <div style={{ display: 'flex', gap: 'var(--space-6)', alignItems: 'flex-start' }}>

        {/* LEFT column — 40%, max 800px */}
        <div style={{
          flex: '0 0 40%', maxWidth: 800, minWidth: 0,
          display: 'flex', flexDirection: 'column', gap: 'var(--space-5)',
        }}>

          {/* Account Information */}
          <Card title="Account Information" icon={<Icon name="staff" size={15} color="var(--color-primary)" />}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-5)' }}>
              {langLabel && <InfoField label="Language">{langLabel}</InfoField>}
              {billingAddr && <InfoField label="Billing Address">{billingAddr}</InfoField>}
              {customer.vat_number && (
                <InfoField label="VAT Number">
                  <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)' }}>
                    {customer.vat_number}
                  </span>
                </InfoField>
              )}
              {customer.website && (
                <InfoField label="Website">
                  <a
                    href={customer.website}
                    target="_blank"
                    rel="noopener noreferrer"
                    style={{ color: 'var(--color-text-accent)', textDecoration: 'none' }}
                    onMouseEnter={e => e.currentTarget.style.textDecoration = 'underline'}
                    onMouseLeave={e => e.currentTarget.style.textDecoration = 'none'}
                  >
                    {customer.website}
                  </a>
                </InfoField>
              )}
              {tags.length > 0 && (
                <InfoField label="Tags">
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 'var(--space-2)', marginTop: 2 }}>
                    {tags.map(tag => (
                      <span key={tag} style={{
                        padding: '2px var(--space-2)',
                        borderRadius: 'var(--radius-sm)',
                        backgroundColor: 'var(--color-bg-island)',
                        color: 'var(--color-text-secondary)',
                        fontSize: 'var(--font-size-xs)',
                        fontWeight: 'var(--font-weight-semibold)',
                        textTransform: 'uppercase',
                        letterSpacing: 'var(--tracking-wide)',
                        border: '1px solid var(--color-border)',
                      }}>
                        {tag}
                      </span>
                    ))}
                  </div>
                </InfoField>
              )}
              {!langLabel && !billingAddr && !customer.vat_number && tags.length === 0 && (
                <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', margin: 0 }}>
                  No account information yet.
                </p>
              )}
            </div>
          </Card>

          {/* Contact Details */}
          <Card
            title="Contact Details"
            icon={<Icon name="mail" size={15} color="var(--color-primary)" />}
            action={canEdit && (
              <Button variant="ghost" size="sm" onClick={() => navigate(`/crm/customers/${customerId}/edit`)}>
                Edit
              </Button>
            )}
          >
            {contacts.length === 0 ? (
              <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', margin: 0 }}>No contacts on record.</p>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-4)' }}>
                {contacts.map((c, i) => (
                  <ContactRow key={c.id || i} type={c.type} value={c.value} label={c.label} primary={c.primary} />
                ))}
              </div>
            )}
          </Card>

          {/* Staff Notes */}
          <Card
            title="Staff Notes"
            icon={<Icon name="info" size={15} color="var(--color-primary)" />}
            action={canEdit && (
              <Button variant="secondary" size="sm" onClick={() => setNoteModal({ editIndex: null, initialData: null })}>
                + Add Note
              </Button>
            )}
          >
            <StaffNotes
              notes={notes}
              canEdit={canEdit}
              onEdit={(index, note) => setNoteModal({ editIndex: index, initialData: note })}
            />
          </Card>

        </div>

        {/* RIGHT column — flex, expands freely */}
        <div style={{
          flex: 1, minWidth: 0,
          display: 'flex', flexDirection: 'column', gap: 'var(--space-5)',
        }}>

          {/* Latest Orders */}
          <Card
            padding={false}
            title="Latest Orders"
            icon={<Icon name="dashboard" size={15} color="var(--color-primary)" />}
            action={
              <Button variant="ghost" size="sm" onClick={() => onTabChange('orders')}>
                View All
              </Button>
            }
          >

            {ordersLoading ? (
              <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-6)' }}>
                <Spinner size="sm" />
              </div>
            ) : latestOrders.length === 0 ? (
              <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', padding: '0 var(--space-8) var(--space-8)', margin: 0 }}>
                No orders yet.
              </p>
            ) : (
              <div style={{ padding: '0 var(--space-8) var(--space-8)' }}>
              <table style={{ width: '100%', borderCollapse: 'collapse' }}>
                <thead>
                  <tr>
                    {['Order', 'Last Updated', 'Status', 'Value'].map(h => (
                      <th key={h} style={{
                        padding: 'var(--space-2) var(--space-3)',
                        textAlign: h === 'Value' ? 'right' : 'left',
                        fontSize: 'var(--font-size-xs)',
                        fontWeight: 'var(--font-weight-bold)',
                        color: 'var(--color-text-muted)',
                        textTransform: 'uppercase',
                        letterSpacing: 'var(--tracking-wide)',
                        backgroundColor: 'rgba(255,255,255,0.02)',
                        borderTop: '1px solid var(--color-border)',
                        borderBottom: '1px solid var(--color-border)',
                      }}>
                        {h}
                      </th>
                    ))}
                  </tr>
                </thead>
                <tbody>
                  {latestOrders.map(order => {
                    const sm = ORDER_STATUS_META[order.status] || { label: order.status, variant: 'neutral' }
                    const lastUpdated = order.updated_at || order.status_updated_at || order.created_at
                    const value = order.total_value ?? order.total ?? order.amount ?? null
                    return (
                      <tr
                        key={order.id}
                        style={{ cursor: 'pointer', transition: 'background-color var(--transition-fast)' }}
                        onClick={() => onTabChange('orders')}
                        onMouseEnter={e => e.currentTarget.style.backgroundColor = 'var(--color-bg-elevated)'}
                        onMouseLeave={e => e.currentTarget.style.backgroundColor = 'transparent'}
                      >
                        <td style={{ padding: 'var(--space-3) var(--space-3)', borderBottom: '1px solid var(--color-border)' }}>
                          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
                            <span style={{
                              fontSize: 'var(--font-size-base)',
                              fontWeight: 'var(--font-weight-semibold)',
                              color: 'var(--color-text-primary)',
                            }}>
                              {order.title || order.name || order.order_number || `Order #${order.id}`}
                            </span>
                            {order.order_number && (order.title || order.name) && (
                              <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                                {order.order_number}
                              </span>
                            )}
                          </div>
                        </td>
                        <td style={{ padding: 'var(--space-3) var(--space-3)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-secondary)', borderBottom: '1px solid var(--color-border)', whiteSpace: 'nowrap' }}>
                          {lastUpdated ? formatRelative(lastUpdated) : '—'}
                        </td>
                        <td style={{ padding: 'var(--space-3) var(--space-3)', borderBottom: '1px solid var(--color-border)' }}>
                          <StatusBadge variant={sm.variant}>{sm.label}</StatusBadge>
                        </td>
                        <td style={{ padding: 'var(--space-3) var(--space-3)', textAlign: 'right', fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)', borderBottom: '1px solid var(--color-border)', whiteSpace: 'nowrap' }}>
                          {value != null ? formatCurrency(value, order.currency || 'EUR') : <span style={{ color: 'var(--color-text-muted)', fontWeight: 'var(--font-weight-normal)' }}>unavailable</span>}
                        </td>
                      </tr>
                    )
                  })}
                </tbody>
              </table>
              </div>
            )}
          </Card>

          {/* Recent Communications */}
          <Card
            title="Recent Communications"
            icon={<Icon name="mqtt" size={15} color="var(--color-primary)" />}
            action={
              <Button variant="ghost" size="sm" onClick={() => onTabChange('communication')}>
                View All
              </Button>
            }
          >

            {commsLoading ? (
              <div style={{ display: 'flex', justifyContent: 'center', padding: 'var(--space-6) 0' }}>
                <Spinner size="sm" />
              </div>
            ) : recentComms.length === 0 ? (
              <p style={{ fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)', margin: 0 }}>
                No communications on record.
              </p>
            ) : (
              recentComms.map((comm, i) => (
                <CommEntry
                  key={comm.id || i}
                  comm={comm}
                  isLast={i === recentComms.length - 1}
                  onNavigateToComms={() => onTabChange('communication')}
                />
              ))
            )}
          </Card>

        </div>
      </div>

      {/* Keyframes injected once */}
      <style>{`
        @keyframes overview-pulse {
          0%, 100% { opacity: 1; transform: scale(1); }
          50%       { opacity: 0.4; transform: scale(0.75); }
        }
      `}</style>

      {/* Note modal */}
      <NoteModal
        open={noteModal !== null}
        customer={customer}
        editIndex={noteModal?.editIndex ?? null}
        initialData={noteModal?.initialData ?? null}
        onClose={() => setNoteModal(null)}
        onSaved={updated => { setNoteModal(null); onCustomerUpdated(updated) }}
      />
    </div>
  )
}
