/**
 * Mounts once inside AppLayout. Holds the WebSocket connection to /api/phone/ws,
 * matches incoming callers against the customer list, and renders the call popup
 * over whatever page is currently open.
 */
import { useEffect, useCallback, useRef, useState } from 'react'
import { PhoneIncoming, X, Mail, Phone, MessageSquare, Tag,
         ShoppingBag, TrendingUp, Clock, User } from 'lucide-react'
import client from '../api/client'
import usePhoneStore from '../store/phoneStore'

/* ─── Phone normalisation ─────────────────────────────────────────────────── */
function normalisePhone(raw) {
  if (!raw) return ''
  let s = raw.replace(/[\s\-().+]/g, '')
  if (s.startsWith('0030')) s = s.slice(4)
  else if (s.startsWith('30') && s.length > 10) s = s.slice(2)
  return s
}
function phonesMatch(a, b) {
  const na = normalisePhone(a), nb = normalisePhone(b)
  return na.length > 0 && na === nb
}

function buildWsUrl() {
  const proto = window.location.protocol === 'https:' ? 'wss' : 'ws'
  return `${proto}://${window.location.host}/api/phone/ws`
}

/* ─── Helpers ─────────────────────────────────────────────────────────────── */
function formatTime(date) {
  return date.toLocaleTimeString('el-GR', { hour: '2-digit', minute: '2-digit' })
}
function formatDate(dateStr) {
  if (!dateStr) return '—'
  return new Date(dateStr).toLocaleDateString('el-GR', { day: '2-digit', month: 'short', year: 'numeric' })
}
function formatCurrency(n) {
  return `€${Number(n || 0).toFixed(2)}`
}

/* ─── Ripple rings ────────────────────────────────────────────────────────── */
function RippleRings({ color }) {
  return (
    <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
      {[0, 1, 2].map(i => (
        <span key={i} style={{
          position: 'absolute', width: 80, height: 80, borderRadius: '50%',
          border: `2px solid ${color}`, opacity: 0,
          animation: `phoneRipple 2s ease-out ${i * 0.6}s infinite`,
        }} />
      ))}
    </div>
  )
}

/* ─── Known customer modal ────────────────────────────────────────────────── */
function KnownCustomerModal({ call, customer, orders, onClose }) {
  const recent = (orders || []).slice(0, 3)
  return (
    <div style={{ fontFamily: "'DM Sans','Segoe UI',sans-serif" }}>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 9990,
        background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(8px)',
        animation: 'fadeIn 0.2s ease',
      }} />
      <div style={{
        position: 'fixed', zIndex: 9991,
        top: '50%', left: '50%',
        transform: 'translate(-50%,-50%)',
        width: '100%', maxWidth: 480, padding: '0 16px',
        animation: 'slideUp 0.3s cubic-bezier(0.16,1,0.3,1)',
      }}>
        <div style={{
          background: '#0f1117', borderRadius: 20, overflow: 'hidden',
          boxShadow: '0 32px 80px rgba(0,0,0,0.8),0 0 0 1px rgba(255,255,255,0.06)',
        }}>
          <div style={{ height: 3, background: 'linear-gradient(90deg,#d4a853,#f0c87a,#d4a853)' }} />

          <div style={{ padding: '24px 24px 20px', position: 'relative' }}>
            <button onClick={onClose} style={{
              position: 'absolute', top: 20, right: 20,
              width: 32, height: 32, borderRadius: 8,
              background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
              color: '#9ca3af', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}
              onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.12)'; e.currentTarget.style.color = '#fff' }}
              onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; e.currentTarget.style.color = '#9ca3af' }}
            ><X size={14} /></button>

            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 16 }}>
              <div style={{ position: 'relative', width: 44, height: 44 }}>
                <RippleRings color="#d4a853" />
                <div style={{
                  width: 44, height: 44, borderRadius: '50%',
                  background: 'linear-gradient(135deg,#d4a853,#f0c87a)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  position: 'relative', zIndex: 1,
                }}><PhoneIncoming size={18} color="#0f1117" /></div>
              </div>
              <div>
                <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.12em', color: '#d4a853', textTransform: 'uppercase' }}>Εισερχόμενη Κλήση</div>
                <div style={{ fontSize: 12, color: '#6b7280', marginTop: 1 }}>{formatTime(call.at)} · {call.caller}</div>
              </div>
            </div>

            <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
              <div style={{
                width: 56, height: 56, borderRadius: 14, flexShrink: 0,
                background: 'linear-gradient(135deg,#1e293b,#334155)',
                border: '1px solid rgba(212,168,83,0.3)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                fontSize: 22, fontWeight: 700, color: '#d4a853',
              }}>{customer.name?.[0]?.toUpperCase() || '?'}</div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', lineHeight: 1.2, letterSpacing: '-0.01em' }}>{customer.name}</div>
                {customer.nickname && (
                  <div style={{ fontSize: 13, color: '#d4a853', marginTop: 2, display: 'flex', alignItems: 'center', gap: 4 }}>
                    <Tag size={11} />{customer.nickname}
                  </div>
                )}
              </div>
            </div>
          </div>

          <div style={{ height: 1, background: 'rgba(255,255,255,0.06)', margin: '0 24px' }} />

          <div style={{ padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 10 }}>
            {customer.email && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Mail size={13} color="#6b7280" style={{ flexShrink: 0 }} />
                <span style={{ fontSize: 13, color: '#d1d5db' }}>{customer.email}</span>
              </div>
            )}
            {customer.phone && (
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <Phone size={13} color="#6b7280" style={{ flexShrink: 0 }} />
                <span style={{ fontSize: 13, color: '#d1d5db', fontVariantNumeric: 'tabular-nums' }}>{customer.phone}</span>
              </div>
            )}
            {customer.notes && (
              <div style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 2 }}>
                <MessageSquare size={13} color="#6b7280" style={{ flexShrink: 0, marginTop: 1 }} />
                <span style={{ fontSize: 13, color: '#9ca3af', lineHeight: 1.5, fontStyle: 'italic' }}>"{customer.notes}"</span>
              </div>
            )}
          </div>

          <div style={{
            margin: '0 24px',
            background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.07)',
            borderRadius: 12, display: 'grid', gridTemplateColumns: '1fr 1fr',
          }}>
            <div style={{ padding: '12px 16px', borderRight: '1px solid rgba(255,255,255,0.07)' }}>
              <div style={{ fontSize: 10, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Επισκέψεις</div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', display: 'flex', alignItems: 'center', gap: 6 }}>
                <ShoppingBag size={14} color="#d4a853" />{customer.visit_count ?? 0}
              </div>
            </div>
            <div style={{ padding: '12px 16px' }}>
              <div style={{ fontSize: 10, color: '#6b7280', textTransform: 'uppercase', letterSpacing: '0.1em', marginBottom: 4 }}>Σύνολο</div>
              <div style={{ fontSize: 22, fontWeight: 700, color: '#f9fafb', display: 'flex', alignItems: 'center', gap: 6 }}>
                <TrendingUp size={14} color="#d4a853" />{formatCurrency(customer.total_spent)}
              </div>
            </div>
          </div>

          <div style={{ padding: '16px 24px 0' }}>
            <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.1em', color: '#6b7280', textTransform: 'uppercase', marginBottom: 8 }}>Πρόσφατες Παραγγελίες</div>
            {recent.length === 0 ? (
              <div style={{ padding: '12px 14px', borderRadius: 10, background: 'rgba(255,255,255,0.03)', border: '1px dashed rgba(255,255,255,0.08)', fontSize: 12, color: '#4b5563', textAlign: 'center' }}>
                Δεν υπάρχουν παραγγελίες ακόμα
              </div>
            ) : (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                {recent.map(order => (
                  <div key={order.id} style={{
                    display: 'flex', alignItems: 'center', gap: 10,
                    padding: '9px 12px', borderRadius: 10,
                    background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.06)',
                  }}>
                    <Clock size={12} color="#6b7280" style={{ flexShrink: 0 }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12, color: '#d1d5db', fontVariantNumeric: 'tabular-nums' }}>
                        {formatDate(order.opened_at)}
                        {order.table_name && <span style={{ color: '#6b7280' }}> · {order.table_name}</span>}
                      </div>
                      <div style={{ fontSize: 11, color: '#6b7280', marginTop: 1 }}>{order.item_count} είδη</div>
                    </div>
                    <div style={{ fontSize: 13, fontWeight: 600, color: '#d4a853', fontVariantNumeric: 'tabular-nums' }}>{formatCurrency(order.total)}</div>
                  </div>
                ))}
              </div>
            )}
          </div>

          <div style={{ padding: '20px 24px' }}>
            <button onClick={onClose} style={{
              width: '100%', padding: '11px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
              background: 'rgba(212,168,83,0.12)', color: '#d4a853', fontSize: 13, fontWeight: 600,
              letterSpacing: '0.02em', transition: 'all 0.15s',
            }}
              onMouseEnter={e => { e.currentTarget.style.background = 'rgba(212,168,83,0.2)' }}
              onMouseLeave={e => { e.currentTarget.style.background = 'rgba(212,168,83,0.12)' }}
            >Κλείσιμο</button>
          </div>
        </div>
      </div>
    </div>
  )
}

/* ─── Unknown caller modal ────────────────────────────────────────────────── */
function UnknownCallerModal({ call, onClose }) {
  return (
    <div style={{ fontFamily: "'DM Sans','Segoe UI',sans-serif" }}>
      <div onClick={onClose} style={{
        position: 'fixed', inset: 0, zIndex: 9990,
        background: 'rgba(0,0,0,0.65)', backdropFilter: 'blur(8px)',
        animation: 'fadeIn 0.2s ease',
      }} />
      <div style={{
        position: 'fixed', zIndex: 9991,
        top: '50%', left: '50%',
        transform: 'translate(-50%,-50%)',
        width: '100%', maxWidth: 360, padding: '0 16px',
        animation: 'slideUp 0.3s cubic-bezier(0.16,1,0.3,1)',
      }}>
        <div style={{
          background: '#0f1117', borderRadius: 20, overflow: 'hidden',
          boxShadow: '0 32px 80px rgba(0,0,0,0.8),0 0 0 1px rgba(255,255,255,0.06)',
        }}>
          <div style={{ height: 3, background: 'linear-gradient(90deg,#3b82f6,#6366f1,#3b82f6)' }} />
          <div style={{ padding: '28px 24px 24px', position: 'relative' }}>
            <button onClick={onClose} style={{
              position: 'absolute', top: 20, right: 20,
              width: 32, height: 32, borderRadius: 8,
              background: 'rgba(255,255,255,0.07)', border: '1px solid rgba(255,255,255,0.1)',
              color: '#9ca3af', cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}
              onMouseEnter={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.12)'; e.currentTarget.style.color = '#fff' }}
              onMouseLeave={e => { e.currentTarget.style.background = 'rgba(255,255,255,0.07)'; e.currentTarget.style.color = '#9ca3af' }}
            ><X size={14} /></button>

            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20 }}>
              <div style={{ position: 'relative', width: 44, height: 44 }}>
                <RippleRings color="#3b82f6" />
                <div style={{
                  width: 44, height: 44, borderRadius: '50%',
                  background: 'linear-gradient(135deg,#1d4ed8,#3b82f6)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  position: 'relative', zIndex: 1,
                }}><PhoneIncoming size={18} color="#fff" /></div>
              </div>
              <div>
                <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: '0.12em', color: '#3b82f6', textTransform: 'uppercase' }}>Εισερχόμενη Κλήση</div>
                <div style={{ fontSize: 12, color: '#6b7280', marginTop: 1 }}>{formatTime(call.at)}</div>
              </div>
            </div>

            <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, padding: '20px 0 8px' }}>
              <div style={{
                width: 56, height: 56, borderRadius: 14,
                background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.08)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}><User size={24} color="#4b5563" /></div>
              <div style={{ fontSize: 12, color: '#6b7280' }}>Άγνωστος καλών</div>
              <div style={{ fontSize: 28, fontWeight: 700, color: '#f9fafb', letterSpacing: '0.02em', fontVariantNumeric: 'tabular-nums' }}>
                {call.caller || '—'}
              </div>
              {call.ext && <div style={{ fontSize: 12, color: '#6b7280' }}>Εσωτερικό: {call.ext}</div>}
            </div>

            <div style={{ marginTop: 20 }}>
              <button onClick={onClose} style={{
                width: '100%', padding: '11px 0', borderRadius: 10, border: 'none', cursor: 'pointer',
                background: 'rgba(59,130,246,0.1)', color: '#3b82f6', fontSize: 13, fontWeight: 600,
                transition: 'all 0.15s',
              }}
                onMouseEnter={e => { e.currentTarget.style.background = 'rgba(59,130,246,0.18)' }}
                onMouseLeave={e => { e.currentTarget.style.background = 'rgba(59,130,246,0.1)' }}
              >Κλείσιμο</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

/* ─── PhoneListener ───────────────────────────────────────────────────────── */
export default function PhoneListener() {
  const { activeCall, dismissCall, setActiveCall, addCallToLog } = usePhoneStore()
  const [customers, setCustomers] = useState([])

  useEffect(() => {
    client.get('/api/customers/')
      .then(r => setCustomers(r.data || []))
      .catch(() => {})
  }, [])

  const handleIncoming = useCallback(async ({ caller, ext }) => {
    const at = new Date()
    const matched = customers.find(c => phonesMatch(c.phone, caller))
    let orders = null
    if (matched) {
      try {
        const r = await client.get(`/api/customers/${matched.id}/orders`)
        orders = r.data?.orders ?? []
      } catch { orders = [] }
    }
    const entry = { caller, ext, at, customer: matched || null, orders }
    addCallToLog(entry)
    setActiveCall(entry)
  }, [customers, addCallToLog, setActiveCall])

  useEffect(() => {
    let ws, dead = false
    function connect() {
      if (dead) return
      ws = new WebSocket(buildWsUrl())
      ws.onclose = () => { if (!dead) setTimeout(connect, 3000) }
      ws.onerror = () => ws.close()
      ws.onmessage = (ev) => {
        try {
          const data = JSON.parse(ev.data)
          if (data.type === 'incoming_call') handleIncoming({ caller: data.caller, ext: data.ext })
        } catch {}
      }
    }
    connect()
    return () => { dead = true; ws?.close() }
  }, [handleIncoming])

  if (!activeCall) return null

  return (
    <>
      <style>{`
        @keyframes fadeIn { from{opacity:0} to{opacity:1} }
        @keyframes slideUp {
          from{opacity:0;transform:translate(-50%,calc(-50% + 24px))}
          to{opacity:1;transform:translate(-50%,-50%)}
        }
        @keyframes phoneRipple {
          0%{transform:scale(1);opacity:0.6}
          100%{transform:scale(2.8);opacity:0}
        }
      `}</style>
      {activeCall.customer
        ? <KnownCustomerModal call={activeCall} customer={activeCall.customer} orders={activeCall.orders} onClose={dismissCall} />
        : <UnknownCallerModal call={activeCall} onClose={dismissCall} />
      }
    </>
  )
}
