// frontend/src/pages/crm/products/ProductForm.jsx

import { useState, useEffect, useRef } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import api from '@/lib/api'
import { useAuth }    from '@/hooks/useAuth'
import PageHeader     from '@/components/ui/PageHeader'
import Button         from '@/components/ui/Button'
import Card           from '@/components/ui/Card'
import FormField      from '@/components/ui/FormField'
import Icon           from '@/components/ui/Icon'
import Spinner        from '@/components/ui/Spinner'
import ConfirmDialog  from '@/components/ui/ConfirmDialog'

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

const CATEGORY_LABELS = {
  controller:     'Controller',
  striker:        'Striker',
  clock:          'Clock',
  part:           'Part',
  repair_service: 'Repair / Service',
}

const DEFAULT_FORM = {
  name_en:        '',
  name_gr:        '',
  sku:            '',
  category:       'controller',
  description_en: '',
  description_gr: '',
  price:          '',
  currency:       'EUR',
  status:         'active',
  costs: {
    labor_hours: '',
    labor_rate:  '',
    items:       [],
  },
  stock: {
    on_hand:  '',
    reserved: '',
  },
}

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

function numOr(v, fallback = 0) {
  const n = parseFloat(v)
  return isNaN(n) ? fallback : n
}

function computeTotal(costs, priceField = 'price_last') {
  const labor = numOr(costs.labor_hours) * numOr(costs.labor_rate)
  const items = (costs.items || []).reduce(
    (sum, it) => sum + numOr(it.quantity, 1) * numOr(it[priceField] || it.price_last),
    0,
  )
  return labor + items
}

// ─── Sub-components ───────────────────────────────────────────────────────────

function SectionDivider({ label }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)', marginBottom: 'var(--space-4)' }}>
      <span style={{
        fontSize:      'var(--font-size-xs)',
        fontWeight:    'var(--font-weight-semibold)',
        color:         'var(--color-text-muted)',
        textTransform: 'uppercase',
        letterSpacing: 'var(--tracking-wide)',
        whiteSpace:    'nowrap',
      }}>
        {label}
      </span>
      <div style={{ flex: 1, height: '1px', backgroundColor: 'var(--color-border)' }} />
    </div>
  )
}

function StatusToggle({ value, onChange, disabled }) {
  const options = [
    { value: 'active',       label: 'Active',       variant: 'success' },
    { value: 'planned',      label: 'Planned',      variant: 'warning' },
    { value: 'discontinued', label: 'Discontinued', variant: 'danger'  },
  ]

  const colors = {
    success: { active: 'var(--color-success)',  activeBg: 'var(--color-success-bg)'  },
    warning: { active: 'var(--color-warning)',  activeBg: 'var(--color-warning-bg)'  },
    danger:  { active: 'var(--color-danger)',   activeBg: 'var(--color-danger-bg)'   },
  }

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
      <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)' }}>
        Status
      </span>
      <div style={{
        display:      'flex',
        borderRadius: 'var(--radius-md)',
        overflow:     'hidden',
        border:       '1px solid var(--color-border-strong)',
      }}>
        {options.map((opt, idx) => {
          const isActive = value === opt.value
          const c        = colors[opt.variant]
          return (
            <button
              key={opt.value}
              type="button"
              disabled={disabled}
              onClick={() => !disabled && onChange(opt.value)}
              style={{
                flex:            1,
                padding:         'var(--space-2) 0',
                fontSize:        'var(--font-size-sm)',
                fontWeight:      'var(--font-weight-semibold)',
                fontFamily:      'var(--font-family-base)',
                border:          'none',
                borderRight:     idx < options.length - 1 ? '1px solid var(--color-border-strong)' : 'none',
                cursor:          disabled ? 'default' : 'pointer',
                backgroundColor: isActive ? c.activeBg : 'var(--color-bg-abyss)',
                color:           isActive ? c.active   : 'var(--color-text-muted)',
                transition:      'background-color 0.15s, color 0.15s',
              }}
            >
              {opt.label}
            </button>
          )
        })}
      </div>
    </div>
  )
}

function SummaryRow({ label, children }) {
  return (
    <div style={{
      display:         'flex',
      alignItems:      'center',
      justifyContent:  'space-between',
      padding:         'var(--space-2) var(--space-3)',
      borderRadius:    'var(--radius-md)',
      backgroundColor: 'var(--color-bg-abyss)',
      fontSize:        'var(--font-size-sm)',
    }}>
      <span style={{ color: 'var(--color-text-muted)' }}>{label}</span>
      {children}
    </div>
  )
}

// ─── ProductForm ──────────────────────────────────────────────────────────────

export default function ProductForm() {
  const { id }   = useParams()
  const isEdit   = Boolean(id)
  const navigate = useNavigate()
  const { hasPermission } = useAuth()
  const canEdit  = hasPermission('crm_products', 'edit')
  const fileRef  = useRef(null)

  const [form,          setForm]          = useState(DEFAULT_FORM)
  const [loading,       setLoading]       = useState(isEdit)
  const [saving,        setSaving]        = useState(false)
  const [error,         setError]         = useState('')
  const [photoPreview,  setPhotoPreview]  = useState(null)
  const [photoFile,     setPhotoFile]     = useState(null)
  const [existingPhoto, setExistingPhoto] = useState(null)
  const [showDelete,    setShowDelete]    = useState(false)
  const [deleting,      setDeleting]      = useState(false)

  // ── Load existing product ──────────────────────────────────────────────────

  useEffect(() => {
    if (!isEdit) return
    api.get(`/crm/products/${id}`)
      .then((data) => {
        setForm({
          name_en:        data.name_en || data.name || '',
          name_gr:        data.name_gr || data.name || '',
          sku:            data.sku || '',
          category:       data.category || 'controller',
          description_en: data.description_en || data.description || '',
          description_gr: data.description_gr || '',
          price:          data.price != null ? String(data.price) : '',
          currency:       data.currency || 'EUR',
          status:         data.status || (data.active !== false ? 'active' : 'discontinued'),
          costs: {
            labor_hours: data.costs?.labor_hours != null ? String(data.costs.labor_hours) : '',
            labor_rate:  data.costs?.labor_rate  != null ? String(data.costs.labor_rate)  : '',
            items: (data.costs?.items || []).map((it) => ({
              name:       it.name || '',
              quantity:   String(it.quantity ?? 1),
              price_last: String(it.price_last ?? it.price ?? ''),
              price_min:  String(it.price_min  ?? ''),
              price_max:  String(it.price_max  ?? ''),
            })),
          },
          stock: {
            on_hand:  data.stock?.on_hand  != null ? String(data.stock.on_hand)  : '',
            reserved: data.stock?.reserved != null ? String(data.stock.reserved) : '',
          },
        })
        if (data.photo_url) setExistingPhoto(`/api${data.photo_url}`)
      })
      .catch((err) => setError(err.message || 'Failed to load product.'))
      .finally(() => setLoading(false))
  }, [id, isEdit])

  // ── Setters ───────────────────────────────────────────────────────────────

  const set      = (field, value) => setForm((f) => ({ ...f, [field]: value }))
  const setCost  = (field, value) => setForm((f) => ({ ...f, costs: { ...f.costs, [field]: value } }))
  const setStock = (field, value) => setForm((f) => ({ ...f, stock: { ...f.stock, [field]: value } }))

  const addCostItem = () => setForm((f) => ({
    ...f,
    costs: { ...f.costs, items: [...f.costs.items, { name: '', quantity: '1', price_last: '', price_min: '', price_max: '' }] },
  }))

  const removeCostItem = (i) => setForm((f) => ({
    ...f,
    costs: { ...f.costs, items: f.costs.items.filter((_, idx) => idx !== i) },
  }))

  const setCostItem = (i, field, value) => setForm((f) => ({
    ...f,
    costs: {
      ...f.costs,
      items: f.costs.items.map((it, idx) => idx === i ? { ...it, [field]: value } : it),
    },
  }))

  // ── Photo ──────────────────────────────────────────────────────────────────

  function handlePhotoChange(e) {
    const file = e.target.files?.[0]
    if (!file) return
    setPhotoFile(file)
    setPhotoPreview(URL.createObjectURL(file))
  }

  // ── Build payload ──────────────────────────────────────────────────────────

  const buildPayload = () => ({
    name:           form.name_en.trim() || form.name_gr.trim(),
    sku:            form.sku.trim() || null,
    category:       form.category,
    description:    form.description_en.trim() || null,
    name_en:        form.name_en.trim() || null,
    name_gr:        form.name_gr.trim() || null,
    description_en: form.description_en.trim() || null,
    description_gr: form.description_gr.trim() || null,
    price:          form.price !== '' ? parseFloat(form.price) : null,
    currency:       form.currency,
    status:         form.status,
    active:         form.status === 'active',
    costs: {
      labor_hours: numOr(form.costs.labor_hours),
      labor_rate:  numOr(form.costs.labor_rate),
      items: form.costs.items
        .filter((it) => it.name.trim())
        .map((it) => ({
          name:       it.name.trim(),
          quantity:   numOr(it.quantity, 1),
          price:      numOr(it.price_last),
          price_last: numOr(it.price_last),
          price_min:  numOr(it.price_min),
          price_max:  numOr(it.price_max),
        })),
    },
    stock: {
      on_hand:  parseInt(form.stock.on_hand, 10)  || 0,
      reserved: parseInt(form.stock.reserved, 10) || 0,
    },
  })

  // ── Save ───────────────────────────────────────────────────────────────────

  const handleSave = async () => {
    if (!form.name_en.trim() && !form.name_gr.trim()) {
      setError('Product name (English) is required.')
      return
    }
    setSaving(true)
    setError('')
    try {
      let saved
      if (isEdit) {
        saved = await api.put(`/crm/products/${id}`, buildPayload())
      } else {
        saved = await api.post('/crm/products', buildPayload())
      }
      if (photoFile && saved?.id) {
        const fd = new FormData()
        fd.append('file', photoFile)
        await fetch(`/api/crm/products/${saved.id}/photo`, {
          method:  'POST',
          headers: { Authorization: `Bearer ${localStorage.getItem('access_token')}` },
          body:    fd,
        })
      }
      navigate('/crm/products')
    } catch (err) {
      setError(err.message || 'Failed to save product.')
    } finally {
      setSaving(false)
    }
  }

  // ── Delete ─────────────────────────────────────────────────────────────────

  const handleDelete = async () => {
    setDeleting(true)
    try {
      await api.delete(`/crm/products/${id}`)
      navigate('/crm/products')
    } catch (err) {
      setError(err.message || 'Failed to delete product.')
      setDeleting(false)
      setShowDelete(false)
    }
  }

  // ── Computed values ────────────────────────────────────────────────────────

  const totalEst   = computeTotal(form.costs, 'price_last')
  const totalMin   = computeTotal(form.costs, 'price_min')
  const totalMax   = computeTotal(form.costs, 'price_max')
  const price      = parseFloat(form.price) || 0
  const marginEst  = price - totalEst
  const marginMin  = price - totalMax
  const marginMax  = price - totalMin
  const stockAvail = (parseInt(form.stock.on_hand, 10) || 0) - (parseInt(form.stock.reserved, 10) || 0)
  const currentPhoto = photoPreview || existingPhoto

  // ── Loading state ──────────────────────────────────────────────────────────

  if (loading) {
    return (
      <div className="page-wrapper">
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 'var(--space-16)' }}>
          <Spinner size="lg" />
        </div>
      </div>
    )
  }

  // ─────────────────────────────────────────────────────────────────────────

  return (
    <div className="page-wrapper page-wrapper--centered" style={{ '--page-content-max-width': '2000px' }}>

      <PageHeader
        title={isEdit ? 'Edit Product' : 'New Product'}
        subtitle={isEdit ? form.name_en || form.name_gr || undefined : 'Add a new product to the catalog'}
      >
        <div style={{ display: 'flex', gap: 'var(--space-2)', alignItems: 'center' }}>
          {isEdit && canEdit && (
            <Button variant="danger" size="md" onClick={() => setShowDelete(true)}>
              Delete
            </Button>
          )}
          <Button variant="secondary" size="md" onClick={() => navigate('/crm/products')}>
            Cancel
          </Button>
          {canEdit && (
            <Button variant="primary" size="md" loading={saving} onClick={handleSave}>
              {isEdit ? 'Save Changes' : 'Create Product'}
            </Button>
          )}
        </div>
      </PageHeader>

      {/* Error banner */}
      {error && (
        <div
          role="alert"
          style={{
            backgroundColor: 'var(--color-danger-bg)',
            border:          '1px solid var(--color-danger)',
            borderRadius:    'var(--radius-md)',
            padding:         'var(--space-3) var(--space-4)',
            color:           'var(--color-danger)',
            fontSize:        'var(--font-size-sm)',
          }}
        >
          {error}
        </div>
      )}

      {/* 2-column layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '2fr 3fr', gap: 'var(--space-6)', alignItems: 'start' }}>

        {/* ── LEFT COLUMN ─────────────────────────────────────────────── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>

          {/* Product Details card */}
          <Card title="Product Details" variant="flat">

            {/* Photo upload */}
            <div style={{ display: 'flex', gap: 'var(--space-4)', alignItems: 'flex-start', marginBottom: 'var(--space-5)' }}>
              <div
                onClick={() => canEdit && fileRef.current?.click()}
                style={{
                  width:           100,
                  height:          100,
                  borderRadius:    'var(--radius-lg)',
                  border:          `2px dashed var(--color-border-strong)`,
                  backgroundColor: 'var(--color-bg-abyss)',
                  display:         'flex',
                  alignItems:      'center',
                  justifyContent:  'center',
                  overflow:        'hidden',
                  flexShrink:      0,
                  cursor:          canEdit ? 'pointer' : 'default',
                  transition:      'border-color 0.15s',
                }}
              >
                {currentPhoto ? (
                  <img src={currentPhoto} alt="" style={{ width: '100%', height: '100%', objectFit: 'contain' }} />
                ) : (
                  <Icon name="firmware" size={28} color="var(--color-text-muted)" />
                )}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)', paddingTop: 'var(--space-1)' }}>
                {canEdit && (
                  <Button variant="secondary" size="sm" onClick={() => fileRef.current?.click()}>
                    {currentPhoto ? 'Change Photo' : 'Upload Photo'}
                  </Button>
                )}
                <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                  JPG, PNG or WebP
                </span>
                {photoFile && (
                  <span style={{ fontSize: 'var(--font-size-xs)', color: 'var(--color-text-muted)' }}>
                    {photoFile.name}
                  </span>
                )}
                <input
                  ref={fileRef}
                  type="file"
                  accept="image/jpeg,image/png,image/webp"
                  style={{ display: 'none' }}
                  onChange={handlePhotoChange}
                />
              </div>
            </div>

            {/* Names */}
            <SectionDivider label="Names" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-4)' }}>
              <FormField
                label="English *"
                name="name_en"
                value={form.name_en}
                onChange={(e) => set('name_en', e.target.value)}
                placeholder="e.g. Vesper Plus"
                required
                disabled={!canEdit}
              />
              <FormField
                label="Greek"
                name="name_gr"
                value={form.name_gr}
                onChange={(e) => set('name_gr', e.target.value)}
                placeholder="π.χ. Vesper Plus"
                disabled={!canEdit}
              />
            </div>

            {/* SKU + Category */}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-4)' }}>
              <FormField
                label="SKU"
                name="sku"
                value={form.sku}
                onChange={(e) => set('sku', e.target.value)}
                placeholder="e.g. VSP-001"
                disabled={!canEdit}
              />
              <FormField
                label="Category"
                name="category"
                type="select"
                value={form.category}
                onChange={(e) => set('category', e.target.value)}
                disabled={!canEdit}
              >
                {Object.entries(CATEGORY_LABELS).map(([val, label]) => (
                  <option key={val} value={val}>{label}</option>
                ))}
              </FormField>
            </div>

            {/* Descriptions */}
            <SectionDivider label="Descriptions" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-4)' }}>
              <FormField
                label="Description — English"
                name="description_en"
                type="textarea"
                rows={3}
                value={form.description_en}
                onChange={(e) => set('description_en', e.target.value)}
                placeholder="Optional product description in English…"
                disabled={!canEdit}
              />
              <FormField
                label="Description — Greek"
                name="description_gr"
                type="textarea"
                rows={3}
                value={form.description_gr}
                onChange={(e) => set('description_gr', e.target.value)}
                placeholder="Προαιρετική περιγραφή…"
                disabled={!canEdit}
              />
            </div>

            {/* Status */}
            <StatusToggle
              value={form.status}
              onChange={(v) => set('status', v)}
              disabled={!canEdit}
            />
          </Card>

          {/* Stock card */}
          <Card title="Stock" variant="flat">
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 'var(--space-4)' }}>
              <FormField
                label="On Hand"
                name="stock_on_hand"
                type="number"
                value={form.stock.on_hand}
                onChange={(e) => setStock('on_hand', e.target.value)}
                placeholder="0"
                inputProps={{ min: 0, step: 1 }}
                disabled={!canEdit}
              />
              <FormField
                label="Reserved"
                name="stock_reserved"
                type="number"
                value={form.stock.reserved}
                onChange={(e) => setStock('reserved', e.target.value)}
                placeholder="0"
                inputProps={{ min: 0, step: 1 }}
                disabled={!canEdit}
              />
              {/* Available — read-only derived */}
              <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
                <span style={{ fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-medium)', color: 'var(--color-text-secondary)' }}>
                  Available
                </span>
                <div
                  className="input"
                  style={{
                    color:      stockAvail > 0 ? 'var(--color-text-primary)' : 'var(--color-warning)',
                    fontWeight: 'var(--font-weight-semibold)',
                    cursor:     'default',
                    userSelect: 'none',
                  }}
                >
                  {stockAvail}
                </div>
              </div>
            </div>
          </Card>

        </div>

        {/* ── RIGHT COLUMN ────────────────────────────────────────────── */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-6)' }}>

          {/* Pricing & Mfg. Costs card */}
          <Card title="Pricing & Manufacturing Costs" variant="flat">

            {/* Price */}
            <SectionDivider label="Pricing" />
            <div style={{ display: 'grid', gridTemplateColumns: '180px 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-5)' }}>
              <FormField
                label="Sale Price (EUR)"
                name="price"
                type="number"
                value={form.price}
                onChange={(e) => set('price', e.target.value)}
                onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) set('price', v.toFixed(2)) }}
                placeholder="0.00"
                inputProps={{ min: 0, step: 0.01 }}
                disabled={!canEdit}
              />
              <div />
            </div>

            {/* Labor */}
            <SectionDivider label="Labor" />
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--space-4)', marginBottom: 'var(--space-5)' }}>
              <FormField
                label="Labor Hours"
                name="labor_hours"
                type="number"
                value={form.costs.labor_hours}
                onChange={(e) => setCost('labor_hours', e.target.value)}
                placeholder="0"
                inputProps={{ min: 0, step: 0.5 }}
                disabled={!canEdit}
              />
              <FormField
                label="Labor Rate (€/hr)"
                name="labor_rate"
                type="number"
                value={form.costs.labor_rate}
                onChange={(e) => setCost('labor_rate', e.target.value)}
                placeholder="0.00"
                inputProps={{ min: 0, step: 0.01 }}
                disabled={!canEdit}
              />
            </div>

            {/* Cost line items */}
            <SectionDivider label="Material Costs" />

            {form.costs.items.length > 0 && (
              <div style={{ marginBottom: 'var(--space-3)' }}>
                {/* Header row */}
                <div style={{
                  display:       'grid',
                  gridTemplateColumns: '1fr 72px 88px 88px 88px 28px',
                  gap:           'var(--space-2)',
                  marginBottom:  'var(--space-2)',
                  paddingBottom: 'var(--space-2)',
                  borderBottom:  '1px solid var(--color-border)',
                }}>
                  {['Item Name', 'Qty', 'Min (€)', 'Max (€)', 'Est. (€)', ''].map((h) => (
                    <span key={h} style={{
                      fontSize:      'var(--font-size-xs)',
                      fontWeight:    'var(--font-weight-semibold)',
                      color:         'var(--color-text-muted)',
                      textTransform: 'uppercase',
                      letterSpacing: 'var(--tracking-wide)',
                      textAlign:     h === 'Qty' || h === 'Min (€)' || h === 'Max (€)' || h === 'Est. (€)' ? 'center' : 'left',
                    }}>
                      {h}
                    </span>
                  ))}
                </div>

                {/* Item rows */}
                {form.costs.items.map((it, i) => (
                  <div key={i} style={{
                    display:  'grid',
                    gridTemplateColumns: '1fr 72px 88px 88px 88px 28px',
                    gap:      'var(--space-2)',
                    marginBottom: 'var(--space-2)',
                  }}>
                    <input
                      className="input"
                      value={it.name}
                      onChange={(e) => setCostItem(i, 'name', e.target.value)}
                      placeholder="e.g. PCB"
                      disabled={!canEdit}
                    />
                    <input
                      className="input"
                      type="number" min="0" step="1"
                      value={it.quantity}
                      onChange={(e) => setCostItem(i, 'quantity', e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, 'quantity', v.toFixed(2)) }}
                      style={{ textAlign: 'center' }}
                      disabled={!canEdit}
                    />
                    <input
                      className="input"
                      type="number" min="0" step="0.01"
                      value={it.price_min}
                      onChange={(e) => setCostItem(i, 'price_min', e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, 'price_min', v.toFixed(2)) }}
                      style={{ textAlign: 'center' }}
                      placeholder="0.00"
                      disabled={!canEdit}
                    />
                    <input
                      className="input"
                      type="number" min="0" step="0.01"
                      value={it.price_max}
                      onChange={(e) => setCostItem(i, 'price_max', e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, 'price_max', v.toFixed(2)) }}
                      style={{ textAlign: 'center' }}
                      placeholder="0.00"
                      disabled={!canEdit}
                    />
                    <input
                      className="input"
                      type="number" min="0" step="0.01"
                      value={it.price_last}
                      onChange={(e) => setCostItem(i, 'price_last', e.target.value)}
                      onBlur={(e) => { const v = parseFloat(e.target.value); if (!isNaN(v)) setCostItem(i, 'price_last', v.toFixed(2)) }}
                      style={{ textAlign: 'center' }}
                      placeholder="0.00"
                      disabled={!canEdit}
                    />
                    {canEdit && (
                      <button
                        type="button"
                        onClick={() => removeCostItem(i)}
                        style={{
                          display:         'flex',
                          alignItems:      'center',
                          justifyContent:  'center',
                          background:      'none',
                          border:          'none',
                          cursor:          'pointer',
                          color:           'var(--color-danger)',
                          padding:         0,
                          opacity:         0.7,
                        }}
                        aria-label="Remove item"
                      >
                        <Icon name="close" size={14} />
                      </button>
                    )}
                  </div>
                ))}
              </div>
            )}

            {canEdit && (
              <Button
                variant="ghost"
                size="sm"
                onClick={addCostItem}
                style={{ marginBottom: 'var(--space-5)' }}
                icon={
                  <svg width="11" height="11" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" aria-hidden="true">
                    <path d="M6 1v10M1 6h10" />
                  </svg>
                }
              >
                Add Cost Item
              </Button>
            )}

            {/* Summary */}
            <div style={{ display: 'flex', flexDirection: 'column', gap: 'var(--space-2)' }}>
              <SummaryRow label="Mfg. Cost Total">
                <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
                  <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
                    €{totalMin.toFixed(2)} – €{totalMax.toFixed(2)}
                  </span>
                  <span style={{ color: 'var(--color-border-strong)', fontSize: 'var(--font-size-xs)' }}>|</span>
                  <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', fontWeight: 'var(--font-weight-semibold)', color: 'var(--color-text-primary)' }}>
                    est. €{totalEst.toFixed(2)}
                  </span>
                </div>
              </SummaryRow>

              <SummaryRow label="Margin (Price − Cost)">
                {form.price ? (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 'var(--space-3)' }}>
                    <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>
                      €{marginMax.toFixed(2)} – €{marginMin.toFixed(2)}
                    </span>
                    <span style={{ color: 'var(--color-border-strong)', fontSize: 'var(--font-size-xs)' }}>|</span>
                    <span style={{
                      fontFamily: 'var(--font-family-mono)',
                      fontSize:   'var(--font-size-sm)',
                      fontWeight: 'var(--font-weight-semibold)',
                      color:      marginEst >= 0 ? 'var(--color-success)' : 'var(--color-danger)',
                    }}>
                      est. €{marginEst.toFixed(2)}
                    </span>
                  </div>
                ) : (
                  <span style={{ fontFamily: 'var(--font-family-mono)', fontSize: 'var(--font-size-sm)', color: 'var(--color-text-muted)' }}>—</span>
                )}
              </SummaryRow>
            </div>

          </Card>
        </div>
      </div>

      {/* Delete confirm */}
      <ConfirmDialog
        open={showDelete}
        onClose={() => setShowDelete(false)}
        onConfirm={handleDelete}
        title="Delete Product"
        message={`Permanently delete "${form.name_en || form.name_gr}"? This cannot be undone.`}
        confirmLabel="Delete Product"
        variant="danger"
        loading={deleting}
        persistent={deleting}
      />

    </div>
  )
}
