/* Kanban — pipeline com cards compactos e ricos em info */

class KanbanErrorBoundary extends React.Component {
  constructor(props) { super(props); this.state = { hasError: false, errorMsg: '' }; }
  static getDerivedStateFromError(error) { return { hasError: true, errorMsg: error.message }; }
  render() {
    if (this.state.hasError) return <div style={{ padding: 40, color: 'red' }}>Erro Fatal: {this.state.errorMsg}</div>;
    return this.props.children;
  }
}

const KanbanCard = ({ lead, onClick }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const tempColor = { quente: t.orange, morno: t.primary, frio: t.textDim, fechado: t.green }[lead.temp] || t.textDim;
  return (
    <div draggable title="Clique para ver os detalhes do cliente"
      onDragStart={(e) => {
        e.dataTransfer.setData('leadId', lead.id);
        e.dataTransfer.effectAllowed = 'move';
      }}
      onClick={onClick} style={{
      background: t.surface,
      border: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      borderRadius: t.radiusMd,
      padding: 12, marginBottom: 10, cursor: 'pointer',
      boxShadow: isBloom ? '3px 3px 0 0 #14131A' : '0 1px 0 rgba(255,255,255,0.04) inset',
      transition: 'transform 0.1s, box-shadow 0.1s',
      position: 'relative',
    }}
    onMouseEnter={(e) => {
      e.currentTarget.style.transform = isBloom ? 'translate(-1px, -1px)' : 'translateY(-1px)';
      e.currentTarget.style.boxShadow = isBloom ? '5px 5px 0 0 #14131A' : '0 4px 16px -4px rgba(0,0,0,0.4)';
    }}
    onMouseLeave={(e) => {
      e.currentTarget.style.transform = '';
      e.currentTarget.style.boxShadow = isBloom ? '3px 3px 0 0 #14131A' : '0 1px 0 rgba(255,255,255,0.04) inset';
    }}>
      {/* Header: avatar + name + score */}
      <div style={{ display: 'flex', alignItems: 'center', gap: 9, marginBottom: 10 }}>
        <Avatar name={lead.avatar} color={lead.color} size={30} ai={lead.aiActive}/>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 13, fontWeight: 600, color: t.text, letterSpacing: '-0.01em',
            overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{lead.name}</div>
          <div style={{ fontSize: 10.5, color: t.textMuted, fontFamily: t.fontMono }}>{lead.city}</div>
        </div>
        <ScoreRing value={lead.score} size={30}/>
      </div>

      {/* Last message snippet */}
      <div style={{
        padding: 9, borderRadius: t.radiusSm,
        background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.025)',
        border: isBloom ? `1.5px solid ${t.border}` : 'none',
        fontSize: 11.5, color: t.textMuted, lineHeight: 1.4, marginBottom: 10,
        display: '-webkit-box', WebkitLineClamp: 2, WebkitBoxOrient: 'vertical', overflow: 'hidden',
      }}>
        {lead.lastMsg}
      </div>

      {/* AI summary */}
      {lead.nextAction && (
        <div style={{
          display: 'flex', gap: 6, padding: '7px 9px', borderRadius: t.radiusSm,
          background: isBloom ? t.primarySoft : 'rgba(91,141,239,0.08)',
          border: isBloom ? `1.5px solid ${t.border}` : '1px solid rgba(91,141,239,0.18)',
          marginBottom: 10,
        }}>
          <Icons.Sparkles size={11} stroke={isBloom ? t.text : t.primary} style={{ marginTop: 2, flexShrink: 0 }}/>
          <div style={{ fontSize: 10.5, color: isBloom ? t.text : t.text, lineHeight: 1.4, fontWeight: 500 }}>
            <span style={{ color: isBloom ? t.text : t.primary, fontWeight: 700, fontFamily: t.fontMono, fontSize: 9, letterSpacing: '0.06em' }}>
              PRÓX. AÇÃO ·{' '}
            </span>
            {lead.nextAction}
          </div>
        </div>
      )}

      {/* Footer: value, tags, time */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 6, marginBottom: 8 }}>
        <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>
          {lead.tags.slice(0,2).map(tag => (
            <span key={tag} style={{
              padding: '2px 6px', borderRadius: 4, fontSize: 10, fontWeight: 600,
              background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.04)',
              color: t.textMuted,
              border: isBloom ? `1.5px solid ${t.border}` : 'none',
            }}>{tag}</span>
          ))}
        </div>
        {lead.value_cents > 0 && (
          <span style={{ fontFamily: t.fontMono, fontSize: 12, fontWeight: 700, color: t.text, letterSpacing: '-0.01em' }}>
            R$ {(lead.value_cents/100).toLocaleString('pt-BR')}
          </span>
        )}
      </div>

      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        paddingTop: 8,
        borderTop: isBloom ? `1.5px dashed ${t.border}` : `1px dashed ${t.border}`,
      }}>
        <Pill soft={tempColor + (isBloom ? '' : '22')} color={isBloom ? t.text : tempColor} style={{ padding: '2px 7px', fontSize: 10 }}>
          {lead.temp === 'quente' && <Icons.Fire size={9} stroke={isBloom ? t.text : tempColor}/>}
          {lead.temp === 'morno' && <span style={{width:6,height:6,borderRadius:'50%',background:tempColor}}/>}
          {lead.temp === 'frio' && <span style={{width:6,height:6,borderRadius:'50%',background:tempColor}}/>}
          {lead.temp === 'fechado' && <Icons.Check size={9} stroke={isBloom ? t.text : tempColor}/>}
          {lead.temp}
        </Pill>
        <div style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10.5, color: t.textMuted, fontFamily: t.fontMono }}>
          <Icons.Clock size={10}/> {lead.lastTime}
        </div>
      </div>

      {/* Unread badge */}
      {lead.unread > 0 && (
        <div style={{
          position: 'absolute', top: -6, right: -6,
          width: 20, height: 20, borderRadius: '50%',
          background: t.green, color: '#fff',
          fontSize: 11, fontWeight: 700, fontFamily: t.fontMono,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          border: isBloom ? `1.5px solid ${t.border}` : `2px solid ${t.bg}`,
          boxShadow: isBloom ? '2px 2px 0 0 #14131A' : '0 2px 8px rgba(16,185,129,0.5)',
        }}>{lead.unread}</div>
      )}
    </div>
  );
};

const KanbanColumn = ({ stage, leads, onOpenLead, onDropLead, onAddLead }) => {
  const t = useTheme();
  const isBloom = t.name === 'BLOOM';
  const I = Icons[stage.icon] || Icons.Check;
  const totalValue = leads.reduce((s, l) => s + (l.value_cents || 0), 0);
  
  const [isDragOver, setIsDragOver] = React.useState(false);

  return (
    <div 
      onDragOver={(e) => { e.preventDefault(); e.dataTransfer.dropEffect = 'move'; setIsDragOver(true); }}
      onDragLeave={() => setIsDragOver(false)}
      onDrop={(e) => {
        e.preventDefault();
        setIsDragOver(false);
        const leadId = e.dataTransfer.getData('leadId');
        if (leadId) onDropLead(leadId, stage.id);
      }}
      style={{
      width: 296, flexShrink: 0,
      background: isBloom ? t.surfaceAlt : 'rgba(255,255,255,0.015)',
      border: isBloom ? (isDragOver ? `2px dashed ${t.primary}` : `1.5px solid ${t.border}`) : (isDragOver ? `1px dashed ${t.primary}` : `1px solid ${t.border}`),
      borderRadius: t.radiusLg, padding: 12,
      display: 'flex', flexDirection: 'column',
      maxHeight: '100%', overflow: 'hidden',
      transition: 'border 0.2s, background 0.2s',
      backgroundColor: isDragOver ? (isBloom ? t.primarySoft : 'rgba(91,141,239,0.05)') : undefined
    }}>
      {/* Column header */}
      <div style={{ marginBottom: 12, paddingBottom: 12,
        borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 7 }}>
          <div style={{
            width: 26, height: 26, borderRadius: isBloom ? 7 : 7,
            background: stage.color + (isBloom ? '' : '22'),
            border: isBloom ? `1.5px solid ${t.border}` : 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
          }}>
            <I size={14} stroke={isBloom ? t.text : stage.color}/>
          </div>
          <span style={{ fontSize: 13.5, fontWeight: 700, color: t.text, letterSpacing: '-0.01em', flex: 1 }}>{stage.label}</span>
          <span style={{
            fontFamily: t.fontMono, fontSize: 11, fontWeight: 700, color: t.text,
            padding: '2px 7px', borderRadius: 6,
            background: isBloom ? t.surface : 'rgba(255,255,255,0.05)',
            border: isBloom ? `1.5px solid ${t.border}` : 'none',
          }}>{leads.length}</span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', fontSize: 11, color: t.textMuted }}>
          <span style={{ fontFamily: t.fontMono }}>R$ {(totalValue/100000).toFixed(1)}K</span>
          <Btn variant="ghost" size="sm" style={{ padding: '2px 6px', fontSize: 11 }} onClick={() => onAddLead && onAddLead(stage.id)}>
            <Icons.Plus size={12}/> add
          </Btn>
        </div>
      </div>

      {/* Cards */}
      <div style={{ flex: 1, overflowY: 'auto', paddingRight: 2, marginRight: -2 }}>
        {leads.map(lead => <KanbanCard key={lead.id} lead={lead} onClick={() => onOpenLead(lead.id)}/>)}
        {leads.length === 0 && (
          <div style={{
            padding: 24, textAlign: 'center', fontSize: 12, color: t.textDim,
            border: isBloom ? `1.5px dashed ${t.border}` : `1px dashed ${t.border}`,
            borderRadius: t.radiusMd,
          }}>
            Nenhum lead nesta etapa
          </div>
        )}
      </div>
    </div>
  );
};

const Kanban = ({ onOpenLead }) => {
  const t = useTheme();
  const { prompt, alert } = useDialog();
  const isBloom = t.name === 'BLOOM';
  const [filter, setFilter] = React.useState('all');
  const [showSearch, setShowSearch] = React.useState(false);
  const [searchQuery, setSearchQuery] = React.useState('');
  const [showFilters, setShowFilters] = React.useState(true);

  const { data: apiLeads, loading: loadingLeads, refetch: refetchLeads } = useLeads();
  const { data: apiStages, loading: loadingStages } = usePipelineStages();
  const moveLeadStage = useMoveLeadStage();

  if (loadingLeads || loadingStages) {
    return <div style={{ padding: 40, color: t.textMuted, textAlign: 'center' }}>Carregando Kanban...</div>;
  }

  let leads = [];
  let stages = window.stagesPipeline || [];
  let filteredLeads = [];
  let grouped = [];
  let renderError = null;

  try {
    leads = (apiLeads && apiLeads.data) ? apiLeads.data : (Array.isArray(apiLeads) ? apiLeads : (window.mockLeads || []));
    stages = (apiStages && apiStages.length > 0) ? apiStages : (window.stagesPipeline || []);

    filteredLeads = leads.filter(l => {
      if (filter === 'hot' && l.temp !== 'quente') return false;
      if (filter === 'ai' && !l.aiActive) return false;
      if (searchQuery && l.name && !l.name.toLowerCase().includes(searchQuery.toLowerCase())) return false;
      return true;
    });

    grouped = stages.map(s => ({
      ...s,
      leads: filteredLeads.filter(l => l.stage === s.id),
    }));
  } catch (err) {
    renderError = err.message;
  }

  if (renderError) {
    return <div style={{ padding: 40, color: 'red' }}>Erro fatal no Kanban: {renderError}</div>;
  }

  const handleDropLead = (leadId, newStageId) => {
    moveLeadStage(leadId, newStageId);
  };

  const handleNovoLead = async (stageId) => {
    const nome = await prompt("Digite o nome do novo Lead (ou cancele):");
    if (!nome) return;
    try {
      await window.FluxoApi.post('/leads', { name: nome, source: 'Kanban Manual', stage: typeof stageId === 'string' ? stageId : 'novo' });
      refetchLeads();
    } catch (e) {
      alert("Erro ao criar lead: " + e.message);
    }
  };

  const totalValue = leads.reduce((s, l) => s + (l.value_cents || 0), 0);
  const avgTicket = leads.length ? (totalValue / leads.length / 100) : 0;

  return (
    <div style={{ padding: '24px 28px 0', height: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18, gap: 16 }}>
        <div>
          <div style={{ fontSize: 11, color: t.textMuted, letterSpacing: '0.14em', fontFamily: t.fontMono, marginBottom: 4 }}>
            PIPELINE COMERCIAL
          </div>
          <h1 style={{ margin: 0, fontFamily: t.fontDisplay, fontSize: 32, fontWeight: 700, letterSpacing: '-0.03em', color: t.text }}>
            Kanban de Atendimentos
          </h1>
          <div style={{ marginTop: 8, display: 'flex', gap: 18, fontSize: 13, color: t.textMuted }}>
            <span><strong style={{color: t.text, fontFamily: t.fontDisplay}}>{leads.length}</strong> leads ativos</span>
            <span>·</span>
            <span><strong style={{color: t.text, fontFamily: t.fontDisplay}}>R$ {(totalValue/100000).toFixed(1)}K</strong> em pipeline</span>
            <span>·</span>
            <span>ticket médio <strong style={{color: t.text, fontFamily: t.fontDisplay}}>R$ {avgTicket.toFixed(0)}</strong></span>
          </div>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12, alignItems: 'flex-end' }}>
          <div style={{ display: 'flex', gap: 8 }}>
            <Btn variant="secondary" icon={<Icons.Filter size={14}/>} onClick={() => setShowFilters(!showFilters)}>
              Filtros
            </Btn>
            <Btn variant="secondary" icon={<Icons.Search size={14}/>} onClick={() => setShowSearch(!showSearch)}>
              Buscar
            </Btn>
            <Btn variant="primary" icon={<Icons.Plus size={14} stroke="#fff"/>} onClick={handleNovoLead}>
              Novo lead
            </Btn>
          </div>
          {showSearch && (
            <input 
              autoFocus
              value={searchQuery}
              onChange={e => setSearchQuery(e.target.value)}
              placeholder="Buscar pelo nome..."
              style={{
                padding: '6px 12px', borderRadius: t.radiusMd, border: `1px solid ${t.border}`,
                background: t.surfaceAlt, color: t.text, outline: 'none', width: 220, fontSize: 13
              }}
            />
          )}
        </div>
      </div>

      {/* Filter tabs */}
      {showFilters && (
        <div style={{ display: 'flex', gap: 6, marginBottom: 16,
          paddingBottom: 16,
          borderBottom: isBloom ? `1.5px solid ${t.border}` : `1px solid ${t.border}`,
        }}>
          <Tab active={filter==='all'} onClick={() => setFilter('all')} count={leads.length}>Todos</Tab>
          <Tab active={filter==='hot'} onClick={() => setFilter('hot')} count={leads.filter(l=>l.temp==='quente').length} color={t.orange}>
            Quentes
          </Tab>
          <Tab active={filter==='ai'} onClick={() => setFilter('ai')} count={leads.filter(l=>l.aiActive).length} color={t.green}>
            IA atendendo
          </Tab>
          <Tab count={2}>Sem resposta &gt;1h</Tab>
          <Tab count={5}>Hoje</Tab>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
            <span style={{ fontSize: 11, color: t.textMuted, fontFamily: t.fontMono, letterSpacing: '0.06em' }}>VISÃO</span>
            <Tab active>Kanban</Tab>
            <Tab>Lista</Tab>
          </div>
        </div>
      )}

      {/* Columns */}
      <div style={{ flex: 1, display: 'flex', gap: 14, overflowX: 'auto', overflowY: 'hidden', paddingBottom: 24 }}>
        {grouped.map(stage => (
          <KanbanColumn key={stage.id} stage={stage} leads={stage.leads} onOpenLead={onOpenLead} onDropLead={handleDropLead} onAddLead={handleNovoLead}/>
        ))}
      </div>
    </div>
  );
};

window.Kanban = Kanban;
