// components.jsx — shared building blocks

// CakeArt — renders one of the seeded SVG cake illustrations
function CakeArt({ name, className = '', style }) {
  const src = window.CAKE_ART[name] || window.CAKE_ART['rose-tier'];
  return (
    <div className={className} style={style}
         dangerouslySetInnerHTML={{ __html: src }} />
  );
}

// StatusBadge
function StatusBadge({ status, size = 'md', orderType }) {
  const labels = orderType ? window.getStatusLabels(orderType) : window.STATUS_LABELS;
  const label = labels[status] || status;
  return (
    <span className={`badge ${status}`} style={size === 'lg' ? { fontSize: 13, padding: '6px 14px' } : null}>
      <span className={`badge-dot dot-${status}`} />
      {label}
    </span>
  );
}

function PaymentBadge({ payment, size = 'md' }) {
  const state = window.paymentState(payment);
  const label = window.paymentLabel(state);
  const dotMap = { unpaid: 'var(--red)', deposit: 'var(--amber)', paid: 'var(--green)' };
  return (
    <span className={`badge ${state}`} style={size === 'lg' ? { fontSize: 13, padding: '6px 14px' } : null}>
      <span className="badge-dot" style={{ background: dotMap[state] }} />
      {label}
    </span>
  );
}

function ConfidenceBar({ score, animate = true }) {
  const pct = Math.round(score * 100);
  const level = score >= 0.85 ? 'high' : score >= 0.65 ? 'medium' : 'low';
  const colors = {
    high: 'var(--green)',
    medium: 'var(--amber)',
    low: 'var(--red)',
  };
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span className="conf-pill" data-level={level} style={{
          background: level === 'high' ? 'var(--green-soft)' : level === 'medium' ? 'var(--amber-soft)' : 'var(--red-soft)',
          color: level === 'high' ? '#285d3f' : level === 'medium' ? '#7a5418' : '#8c2e2e',
        }}>
          <span className="badge-dot" style={{ background: colors[level] }} />
          {level === 'high' ? 'e lartë' : level === 'medium' ? 'mesatare' : 'e ulët'} besueshmëri
        </span>
        <span className="tabular muted" style={{ fontSize: 13 }}>{pct}% përputhje</span>
      </div>
      <div className="confidence-track">
        <div className="confidence-fill" style={{
          width: animate ? `${pct}%` : `${pct}%`,
          background: colors[level],
        }} />
      </div>
    </div>
  );
}

// Avatar
function Avatar({ name, color, size = 'md' }) {
  const initials = (name || '?').split(' ').map(s => s[0]).slice(0, 2).join('').toUpperCase();
  const palette = ['#D4607A', '#4CAF82', '#D89331', '#4B948F', '#7A5AE0', '#3B1F0A'];
  const bg = color || palette[(initials.charCodeAt(0) + (initials.charCodeAt(1) || 0)) % palette.length];
  return (
    <div className={`avatar ${size}`} style={{ background: bg, color: '#FDF8F3' }}>
      {initials}
    </div>
  );
}

// Bell with unread count
function NotificationBell({ count, onClick, active }) {
  return (
    <button className="icon-btn bordered" onClick={onClick} aria-label="Njoftime"
            style={active ? { background: 'var(--cream-2)' } : null}>
      <IconBell size={18} />
      {count > 0 && (
        <span style={{
          position: 'absolute',
          top: -2, right: -2,
          background: 'var(--rose)',
          color: 'white',
          fontSize: 10,
          fontWeight: 700,
          padding: '2px 6px',
          borderRadius: 999,
          minWidth: 18,
          textAlign: 'center',
          border: '2px solid var(--cream)',
          lineHeight: 1,
        }}>{count}</span>
      )}
    </button>
  );
}

// Filter chip row
function FilterChip({ label, count, active, onClick, accent }) {
  return (
    <button className={`chip ${active ? 'active' : ''}`} onClick={onClick}
      style={accent && !active ? { borderColor: accent, color: accent } : accent && active ? { background: accent, borderColor: accent } : undefined}>
      {label}
      {count != null && <span className="count">{count}</span>}
    </button>
  );
}

// Section header
function SectionHeader({ title, subtitle, action }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 14, gap: 16 }}>
      <div>
        <h2 className="display" style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: '-0.01em' }}>{title}</h2>
        {subtitle && <p className="muted" style={{ margin: '4px 0 0', fontSize: 13.5 }}>{subtitle}</p>}
      </div>
      {action}
    </div>
  );
}

// Confirmation dialog
function ConfirmDialog({ open, title, body, confirmLabel = 'Konfirmo', cancelLabel = 'Anulo', danger, onConfirm, onCancel }) {
  if (!open) return null;
  return (
    <div className="dialog-backdrop" onClick={onCancel}>
      <div className="dialog" onClick={(e) => e.stopPropagation()}>
        <h3 className="display" style={{ margin: 0, fontSize: 24, fontWeight: 600, marginBottom: 8 }}>{title}</h3>
        <p style={{ margin: 0, marginBottom: 22, color: 'var(--ink-2)', lineHeight: 1.55 }}>{body}</p>
        <div style={{ display: 'flex', justifyContent: 'flex-end', gap: 10 }}>
          <button className="btn secondary" onClick={onCancel}>{cancelLabel}</button>
          <button className={`btn ${danger ? 'rose' : ''}`} onClick={onConfirm}>{confirmLabel}</button>
        </div>
      </div>
    </div>
  );
}

// Toast
function Toast({ toast, onDismiss }) {
  React.useEffect(() => {
    if (!toast) return;
    const t = setTimeout(onDismiss, 3000);
    return () => clearTimeout(t);
  }, [toast]);
  if (!toast) return null;
  return (
    <div style={{
      position: 'fixed',
      bottom: 24,
      left: '50%',
      transform: 'translateX(-50%)',
      background: 'var(--ink)',
      color: 'var(--cream)',
      padding: '12px 20px',
      borderRadius: 999,
      boxShadow: '0 12px 30px -10px rgba(0,0,0,0.4)',
      display: 'flex',
      alignItems: 'center',
      gap: 10,
      fontSize: 14,
      fontWeight: 500,
      zIndex: 100,
      maxWidth: 'calc(100vw - 32px)',
      animation: 'slideup 240ms cubic-bezier(0.2, 0.9, 0.3, 1)',
    }}>
      <IconCircleCheck size={18} color="var(--green)" />
      {toast.message}
    </div>
  );
}

// Order card
function OrderCard({ order, onClick, currentUser }) {
  const due = window.relativeDay(order.due_date);
  const isUrgent = due === 'Sot' || due === 'Nesër';
  const isOwner = currentUser?.role === 'owner';

  const sizeLabel = (() => {
    const parts = [];
    if (order.diameter) {
      parts.push(`K1: ${order.diameter}cm${order.variant ? ` +${order.variant}` : ''}`);
    }
    if (order.flats && order.flats.length > 0) {
      order.flats.forEach((f, i) => parts.push(`K${i + 2}: ${f.size}cm${f.variant ? ` +${f.variant}` : ''}`));
    }
    return parts.join(' · ');
  })();

  return (
    <div className="order-card" onClick={onClick}>
      {order.image_url && (
        <div className="thumb">
          <img src={`${window.api.baseUrl}${order.image_url}`} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
        </div>
      )}
      <div style={{ flex: 1, minWidth: 0, display: 'flex', flexDirection: 'column', gap: 5 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 8 }}>
          <div className="display" style={{ fontSize: 17, fontWeight: 600, lineHeight: 1.2, letterSpacing: '-0.01em' }}>
            {order.customer_name}
          </div>
          <div style={{
            fontSize: 11.5, fontWeight: 600, flexShrink: 0, whiteSpace: 'nowrap',
            color: isUrgent ? 'var(--rose)' : 'var(--ink-mute)',
            textTransform: 'uppercase', letterSpacing: '0.08em',
          }}>{due}</div>
        </div>

        <div style={{ fontSize: 13, color: 'var(--ink-2)', display: 'flex', gap: 10, flexWrap: 'wrap', alignItems: 'center' }}>
          {order.type === 'baklava' ? (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <IconCake size={13} color="var(--amber)" />
              {order.baklava_data?.sold_as === 'tepsi'
                ? `${order.baklava_data.quantity} tepsi`
                : `${order.baklava_data?.quantity} kg`}
              {' · Bakllava'}
              {order.baklava_data?.sold_as === 'tepsi' &&
               order.baklava_data?.tepsi_owner === 'ours' &&
               !order.baklava_data?.tepsi_returned && (
                <span title="Tepsi nuk është kthyer" style={{ display: 'inline-flex', alignItems: 'center', gap: 3,
                  background: 'rgba(216,147,49,0.15)', color: 'var(--amber)', borderRadius: 4,
                  padding: '1px 5px', fontSize: 11, fontWeight: 600, marginLeft: 2 }}>
                  <IconClock size={10} color="var(--amber)" /> kthim
                </span>
              )}
            </span>
          ) : order.type === 'custom' ? (
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
              <IconSparkle size={13} color="var(--rose)" />Dizajn i personalizuar
            </span>
          ) : (
            <span>{order.flavour} · {order.persons} persona</span>
          )}
          {sizeLabel && (
            <span className="tabular" style={{ fontWeight: 500, color: 'var(--ink-3)' }}>{sizeLabel}</span>
          )}
        </div>

        {order.cake_text ? (
          <div style={{ fontSize: 12, color: 'var(--ink-mute)', fontStyle: 'italic', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            "{order.cake_text}"
          </div>
        ) : null}

        {order.notes ? (
          <div style={{ fontSize: 12, color: 'var(--ink-mute)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>
            {order.notes}
          </div>
        ) : null}

        <div style={{ display: 'flex', gap: 6, marginTop: 2, flexWrap: 'wrap', alignItems: 'center' }}>
          <StatusBadge status={order.status} orderType={order.type} />
          <PaymentBadge payment={order.payment} />
          {order.fridge && (
            <span style={{ fontSize: 11, fontWeight: 600, padding: '2px 8px', borderRadius: 6, background: 'var(--cream-3)', color: 'var(--ink-2)', letterSpacing: '0.04em' }}>
              ❄ {order.fridge}
            </span>
          )}
          <span className="muted tabular" style={{ fontSize: 11, marginLeft: 'auto' }}>#{order.id.slice(-4)}</span>
        </div>
      </div>
    </div>
  );
}

function OrderRow({ order, onClick }) {
  return (
    <div onClick={onClick} style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '12px 14px',
      borderBottom: '1px solid var(--line)', cursor: 'pointer', borderRadius: 8,
    }}
    onMouseEnter={(e) => e.currentTarget.style.background = 'var(--cream-2)'}
    onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
    >
      <div style={{ width: 40, height: 40, borderRadius: 8, overflow: 'hidden', flexShrink: 0 }}>
        <CakeArt name={order.art} style={{ width: '100%', height: '100%' }} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
          <span style={{ fontWeight: 600, fontSize: 14 }}>{order.customer_name}</span>
          <span className="muted" style={{ fontSize: 12 }}>#{order.id.slice(-4)}</span>
        </div>
        <div className="muted" style={{ fontSize: 12.5 }}>
          {order.type === 'custom' ? 'Dizajn i personalizuar' : `${order.flavour} · ${order.persons} persona`} · dorëzim {window.relativeDay(order.due_date).toLowerCase()}
        </div>
      </div>
      <div className="tabular" style={{ fontSize: 15, fontWeight: 600 }}>
        {window.formatEUR(order.payment?.total_price)}
      </div>
      <PaymentBadge payment={order.payment} />
    </div>
  );
}

// ── ContactPicker ──────────────────────────────────────────────────────
// Multi-select platform chooser. State shape:
//   { whatsapp?: string, viber?: string, instagram?: string, phone?: string,
//     custom?: { label: string, value: string } }
// Each platform key present = selected; absent = unselected.
const CONTACT_PLATFORMS = [
  { key: 'whatsapp', label: 'WhatsApp', icon: IconWhatsApp, color: '#25D366', placeholder: '+355 69 …' },
  { key: 'viber', label: 'Viber', icon: IconViber, color: '#7360F2', placeholder: '+355 69 …' },
  { key: 'instagram', label: 'Instagram', icon: IconInstagram, color: '#E1306C', placeholder: '@handle' },
  { key: 'phone', label: 'Telefonatë', icon: IconPhone, color: '#3B1F0A', placeholder: '+355 69 …' },
  { key: 'custom', label: 'Tjetër', icon: IconMessageSquare, color: '#4B948F', placeholder: 'Vlera e kontaktit' },
];

function ContactPicker({ value, onChange }) {
  const contacts = value || {};
  const toggle = (key) => {
    const next = { ...contacts };
    if (next[key] != null) {
      delete next[key];
    } else {
      next[key] = key === 'custom' ? { label: '', value: '' } : '';
    }
    onChange(next);
  };
  const setVal = (key, val) => {
    const next = { ...contacts };
    next[key] = val;
    onChange(next);
  };
  const setCustom = (field, val) => {
    const next = { ...contacts };
    next.custom = { ...(next.custom || {}), [field]: val };
    onChange(next);
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
        {CONTACT_PLATFORMS.map(p => {
          const on = contacts[p.key] != null;
          return (
            <button key={p.key} type="button" onClick={() => toggle(p.key)} style={{
              display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '8px 14px 8px 10px',
              borderRadius: 999,
              border: '1px solid', borderColor: on ? p.color : 'var(--line)',
              background: on ? p.color + '14' : 'transparent',
              color: on ? p.color : 'var(--ink-2)',
              fontSize: 13.5, fontWeight: 500, cursor: 'pointer',
              transition: 'background 100ms ease, border-color 100ms ease',
              userSelect: 'none',
            }}>
              <span style={{
                width: 18, height: 18, borderRadius: 4,
                border: '1.5px solid', borderColor: on ? p.color : 'var(--line-2)',
                background: on ? p.color : 'transparent',
                display: 'grid', placeItems: 'center',
                transition: 'all 100ms ease',
              }}>
                {on && <IconCheck size={12} color="white" />}
              </span>
              <p.icon size={14} color={on ? p.color : 'var(--ink-2)'} />
              {p.label}
            </button>
          );
        })}
      </div>

      {CONTACT_PLATFORMS.filter(p => contacts[p.key] != null).length > 0 && (
        <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
          {CONTACT_PLATFORMS.filter(p => contacts[p.key] != null).map(p => (
            <div key={p.key} style={{
              display: 'flex', gap: 8, alignItems: 'center',
              background: 'var(--cream)',
              border: '1px solid var(--line)',
              borderRadius: 10,
              padding: '6px 6px 6px 12px',
            }}>
              <span style={{ width: 28, height: 28, borderRadius: 7, display: 'grid', placeItems: 'center', background: p.color + '18', flexShrink: 0 }}>
                <p.icon size={14} color={p.color} />
              </span>
              {p.key === 'custom' ? (
                <>
                  <input
                    type="text"
                    placeholder="Emri i kanalit (p.sh. TikTok DM)"
                    value={contacts.custom?.label || ''}
                    onChange={(e) => setCustom('label', e.target.value)}
                    style={{ border: 'none', background: 'transparent', outline: 'none', fontSize: 14, fontWeight: 500, color: 'var(--ink)', minWidth: 0, flex: 1, padding: '6px 0' }}
                  />
                  <span style={{ color: 'var(--ink-mute)', fontSize: 13 }}>·</span>
                  <input
                    type="text"
                    placeholder="Vlera"
                    value={contacts.custom?.value || ''}
                    onChange={(e) => setCustom('value', e.target.value)}
                    style={{ border: 'none', background: 'transparent', outline: 'none', fontSize: 14, color: 'var(--ink)', minWidth: 0, flex: 1, padding: '6px 0' }}
                  />
                </>
              ) : (
                <input
                  type="text"
                  placeholder={p.placeholder}
                  value={contacts[p.key] || ''}
                  onChange={(e) => setVal(p.key, e.target.value)}
                  style={{ border: 'none', background: 'transparent', outline: 'none', fontSize: 14, color: 'var(--ink)', flex: 1, minWidth: 0, padding: '6px 0' }}
                />
              )}
              <button onClick={() => toggle(p.key)} className="icon-btn" style={{ width: 28, height: 28, flexShrink: 0 }} title="Hiq">
                <IconX size={12} />
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function contactHref(key, value) {
  if (!value) return null;
  const digits = String(value).replace(/[^\d]/g, '');
  switch (key) {
    case 'whatsapp':  return `https://wa.me/${digits}`;
    case 'viber':     return `viber://chat?number=%2B${digits}`;
    case 'instagram': return `https://instagram.com/${String(value).replace(/^@/, '')}`;
    case 'phone':     return `tel:${String(value).replace(/\s/g, '')}`;
    default:          return null;
  }
}

// Display a contact value (legacy string or new object) as a row of platform pills
function ContactDisplay({ contact, compact = false }) {
  if (!contact) return <span className="muted">Pa kontakt</span>;
  if (typeof contact === 'string') {
    const isHandle = contact.startsWith('@');
    const p = CONTACT_PLATFORMS.find(p => p.key === (isHandle ? 'instagram' : 'whatsapp'));
    const href = contactHref(p.key, contact);
    const Tag = href ? 'a' : 'span';
    return (
      <Tag href={href} target="_blank" rel="noopener noreferrer"
        style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 14, color: 'var(--ink-2)', textDecoration: 'none' }}>
        <p.icon size={14} color={p.color} /> {contact}
      </Tag>
    );
  }
  const entries = CONTACT_PLATFORMS.filter(p => contact[p.key] != null);
  if (entries.length === 0) return <span className="muted">Pa kontakt</span>;
  return (
    <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, alignItems: 'center' }}>
      {entries.map(p => {
        const v = contact[p.key];
        const label = p.key === 'custom' ? (v.label || 'Tjetër') : p.label;
        const value = p.key === 'custom' ? v.value : v;
        const href = contactHref(p.key, value);
        const Tag = href ? 'a' : 'span';
        return (
          <Tag key={p.key} href={href} target={p.key === 'phone' ? '_self' : '_blank'} rel="noopener noreferrer"
            style={{
              display: 'inline-flex', alignItems: 'center', gap: 6,
              background: p.color + '15',
              color: p.color,
              padding: compact ? '3px 9px 3px 7px' : '5px 12px 5px 9px',
              borderRadius: 999,
              fontSize: compact ? 12 : 13,
              fontWeight: 500,
              textDecoration: 'none',
              cursor: href ? 'pointer' : 'default',
            }}>
            <p.icon size={compact ? 12 : 14} color={p.color} />
            {compact ? value : <><strong style={{ fontWeight: 600 }}>{label}</strong> · {value || <em style={{ opacity: 0.6 }}>e pavendosur</em>}</>}
          </Tag>
        );
      })}
    </div>
  );
}

Object.assign(window, {
  CakeArt, StatusBadge, PaymentBadge, ConfidenceBar, Avatar,
  NotificationBell, FilterChip, SectionHeader, ConfirmDialog, Toast,
  OrderCard, OrderRow, ContactPicker, ContactDisplay, CONTACT_PLATFORMS,
});
