/* global React, Icon, Avatar, fmtAED */
const { useState, useEffect, useMemo } = React;

const TEMP_COLOR = { cold: '#6b7280', warm: '#3b82f6', hot: '#f97316', engaged: '#22c55e' };

function _initialsP(name) {
  if (!name) return '?';
  const parts = String(name).replace(/[._@-]/g, ' ').split(/\s+/).filter(Boolean);
  if (!parts.length) return name.slice(0, 2).toUpperCase();
  if (parts.length === 1) return parts[0].slice(0, 2).toUpperCase();
  return (parts[0][0] + parts[parts.length - 1][0]).toUpperCase();
}
function _colorP(s) {
  const palette = ['#22c55e', '#3b82f6', '#a855f7', '#f97316', '#eab308', '#ec4899', '#06b6d4', '#84cc16'];
  let h = 0;
  for (let i = 0; i < (s || '').length; i++) h = ((h << 5) - h) + s.charCodeAt(i);
  return palette[Math.abs(h) % palette.length];
}

function Pipeline({ goto }) {
  const [tab, setTab] = useState('outbound');
  const [data, setData] = useState({ outbound: null, inbound: null });
  const [draggedId, setDraggedId] = useState(null);
  const [dropStage, setDropStage] = useState(null);
  const [moving, setMoving] = useState(false);

  const load = (which) => {
    fetch(`/api/pipeline?pipeline=${which}`, { credentials: 'include' })
      .then((r) => r.ok ? r.json() : Promise.reject(r.statusText))
      .then((d) => setData((prev) => ({ ...prev, [which]: d })))
      .catch(() => setData((prev) => ({ ...prev, [which]: { columns: [] } })));
  };

  useEffect(() => { load('outbound'); load('inbound'); }, []);

  const active = tab === 'combined'
    ? mergeCombined(data.outbound, data.inbound)
    : data[tab];

  const onDrop = async (stageName) => {
    if (!draggedId || moving) return;
    const allItems = (active?.columns || []).flatMap((c) => c.items.map((i) => ({ ...i, stage: c.stage })));
    const card = allItems.find((c) => c.contact_id === draggedId);
    setDraggedId(null);
    setDropStage(null);
    if (!card || card.stage === stageName) return;
    setMoving(true);
    try {
      await fetch(`/api/pipeline/contacts/${draggedId}/stage`, {
        method: 'POST',
        credentials: 'include',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ stage: stageName }),
      });
      load('outbound');
      load('inbound');
    } finally {
      setMoving(false);
    }
  };

  const totalCount = active?.columns?.reduce((a, c) => a + c.count, 0) || 0;
  const totalValue = active?.columns?.reduce((a, c) => a + (c.value_aed || 0), 0) || 0;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', height: '100%', overflow: 'hidden' }}>
      <div className="page-header">
        <div className="page-header-left">
          <div className="page-eyebrow">Sales</div>
          <h1 className="page-title">Pipeline</h1>
        </div>
        <div className="page-header-right">
          <button className="btn btn-primary" disabled style={{ opacity: 0.5 }}><Icon name="plus" size={12} /> New deal</button>
        </div>
      </div>

      <div className="tabs">
        {[
          { id: 'outbound', label: 'Outbound LinkedIn', count: data.outbound?.columns?.reduce((a, c) => a + c.count, 0) ?? 0 },
          { id: 'inbound', label: 'Inbound Ads', count: data.inbound?.columns?.reduce((a, c) => a + c.count, 0) ?? 0 },
          { id: 'combined', label: 'Combined', count: (data.outbound?.columns?.reduce((a, c) => a + c.count, 0) ?? 0) + (data.inbound?.columns?.reduce((a, c) => a + c.count, 0) ?? 0) },
        ].map((t) => (
          <div key={t.id} className={`tab ${tab === t.id ? 'active' : ''}`} onClick={() => setTab(t.id)}>
            {t.label}<span className="tab-count">{t.count}</span>
          </div>
        ))}
      </div>

      <div style={{ padding: '10px 28px', borderBottom: '1px solid var(--divider)', display: 'flex', alignItems: 'center', gap: 10, fontSize: 11 }}>
        <span style={{ color: 'var(--text-dim)', marginLeft: 'auto' }} className="mono">{totalCount} contacts · AED {fmtAED(totalValue)}</span>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: 16 }}>
        {!active && (
          <div style={{ textAlign: 'center', padding: 60, color: 'var(--text-dim)' }}>Loading…</div>
        )}
        {active && (
          <div style={{ display: 'flex', gap: 10, height: '100%', minWidth: 'min-content' }}>
            {active.columns.map((col) => {
              const isDropTarget = dropStage === col.stage;
              return (
                <div key={col.stage}
                  onDragOver={(e) => { e.preventDefault(); setDropStage(col.stage); }}
                  onDragLeave={() => setDropStage(null)}
                  onDrop={() => onDrop(col.stage)}
                  style={{
                    width: 240, flexShrink: 0, display: 'flex', flexDirection: 'column',
                    background: isDropTarget ? 'rgba(34,197,94,0.05)' : 'transparent',
                    border: '1px dashed', borderColor: isDropTarget ? 'var(--accent)' : 'transparent',
                  }}>
                  <div style={{ padding: '8px 10px', display: 'flex', alignItems: 'center', gap: 8, borderBottom: '1px solid var(--divider)' }}>
                    <span style={{ fontSize: 11, fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.06em', color: 'var(--text)' }}>{col.stage}</span>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--text-dim)', marginLeft: 'auto' }}>{col.count}</span>
                  </div>
                  {col.value_aed > 0 && (
                    <div style={{ padding: '4px 10px', fontSize: 10, color: 'var(--text-dim)' }} className="mono">AED {fmtAED(col.value_aed)}</div>
                  )}
                  <div style={{ flex: 1, padding: '4px 0', display: 'flex', flexDirection: 'column', gap: 6, overflow: 'auto' }}>
                    {col.items.map((c) => (
                      <KanbanCard
                        key={c.contact_id}
                        card={c}
                        onDragStart={() => setDraggedId(c.contact_id)}
                        dragging={draggedId === c.contact_id}
                        goto={goto}
                      />
                    ))}
                    {col.items.length === 0 && (
                      <div style={{ padding: 14, textAlign: 'center', fontSize: 11, color: 'var(--text-dim)', border: '1px dashed var(--divider)', margin: '4px 6px' }}>
                        Drop here
                      </div>
                    )}
                  </div>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function mergeCombined(out, inb) {
  if (!out && !inb) return null;
  if (!out) return inb;
  if (!inb) return out;
  const colsByStage = {};
  for (const c of [...out.columns, ...inb.columns]) {
    if (!colsByStage[c.stage]) colsByStage[c.stage] = { stage: c.stage, count: 0, value_aed: 0, items: [] };
    colsByStage[c.stage].count += c.count;
    colsByStage[c.stage].value_aed += c.value_aed;
    colsByStage[c.stage].items.push(...c.items);
  }
  return { columns: Object.values(colsByStage) };
}

function KanbanCard({ card, onDragStart, dragging, goto }) {
  const tempColor = TEMP_COLOR[card.temperature] || '#6b7280';
  return (
    <div
      draggable
      onDragStart={onDragStart}
      onClick={() => goto('contact', card.contact_id)}
      style={{
        background: 'var(--surface)', border: '1px solid var(--divider)',
        margin: '0 6px', padding: 10, cursor: 'grab',
        opacity: dragging ? 0.4 : 1,
      }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 8 }}>
        <Avatar name={card.name || '?'} initials={_initialsP(card.name)} color={_colorP(card.name || card.contact_id)} size="sm" />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 500, color: 'var(--text)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{card.name || '(unnamed)'}</div>
          <div style={{ fontSize: 10, color: 'var(--text-dim)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{card.company || card.title || '—'}</div>
        </div>
        <div style={{ width: 6, height: 6, borderRadius: '50%', background: tempColor, flexShrink: 0 }} title={card.temperature}></div>
      </div>
      {card.deal_value > 0 && (
        <div className="mono" style={{ fontSize: 13, color: 'var(--accent)', marginBottom: 6 }}>AED {fmtAED(card.deal_value)}</div>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 6, justifyContent: 'space-between', fontSize: 10, color: 'var(--text-dim)' }}>
        <span style={{ textTransform: 'capitalize' }}>{card.source}</span>
      </div>
    </div>
  );
}

Object.assign(window, { Pipeline });
